/**
 * $id:  $
 */
package org.jvnet.lookout.ui.core.controller.job;

import java.util.List;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.ui.progress.IProgressConstants;
import org.jvnet.lookout.core.adapter.CannotSearchException;
import org.jvnet.lookout.core.adapter.SearchAdapter;
import org.jvnet.lookout.core.model.SearchQuery;
import org.jvnet.lookout.core.model.SearchResult;
import org.jvnet.lookout.ui.core.Plugin;
import org.jvnet.lookout.ui.core.tree.TreeObject;
import org.jvnet.lookout.ui.core.tree.adapter.ModelToUIAdapter;
import org.jvnet.lookout.ui.core.util.Utilities;


public class SearchJob extends Job {
	
	private SearchAdapter searchAdapter;
	private ModelToUIAdapter modelToUiAdapter;
	private SearchQuery query;
	private List<TreeObject> uiResults;

    private static String UI_PLUGIN_ID;
    private static Plugin searchUiPlugin;
    private static ImageDescriptor imageDescriptor;
    
	static {
		searchUiPlugin = Plugin.getDefault();
        UI_PLUGIN_ID = Plugin.class.getPackage().getName();

        imageDescriptor = Utilities.getImageDescriptor(
        		Plugin.getResourceString("search-view-icon"), 
        		searchUiPlugin);
	}
	
	public SearchJob(String name, SearchAdapter searchAdapter, ModelToUIAdapter modelToUiAdapter, SearchQuery query) {
		super(name);
		this.searchAdapter = searchAdapter;
		this.modelToUiAdapter = modelToUiAdapter;
		this.query = query;
		setProperty(IProgressConstants.ICON_PROPERTY, imageDescriptor);
	}
	
	@Override
	protected IStatus run(IProgressMonitor monitor) {
		
		if(!monitor.isCanceled()) {
			
			monitor.beginTask(getName() + " searching...", 100);
			
			List<SearchResult> modelResults = null;
			try {
				//Search...
				modelResults = searchAdapter.handleSearchRequest(query);
				
			} catch (CannotSearchException e) {				
				
				return org.jvnet.lookout.core.util.Utilities.createPluginStatus(
						Plugin.getDefault(),
						//CXB_EXTERNALIZE
						getName() + " could not complete search",
						"There was a problem when trying to execute the specified search:",
						IStatus.ERROR,
						e);          				
			}
			
			monitor.worked(50);

			//Adapt to UI..
			uiResults = modelToUiAdapter.adapt(modelResults);
			
			monitor.worked(50);
			monitor.done();
		
			return new Status(IStatus.OK, UI_PLUGIN_ID, IStatus.OK, 
					getName() + " completed searching", null);

		} else {    			
			return new Status(IStatus.WARNING, UI_PLUGIN_ID, IStatus.WARNING, 
					getName() + " search was cancelled during its execution", null);
		}		
	}	
	
	public List<TreeObject> getUiResults() {
		return uiResults;
	}
}
