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

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.ReentrantLock;

import org.eclipse.core.runtime.jobs.IJobChangeEvent;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.core.runtime.jobs.JobChangeAdapter;
import org.eclipse.swt.widgets.Display;
import org.jvnet.lookout.ui.core.controller.SearchController;
import org.jvnet.lookout.ui.core.search.SearchResultsView;
import org.jvnet.lookout.ui.core.tree.SearchResultsContentProvider;
import org.jvnet.lookout.ui.core.tree.TreeObject;

public class SearchJobListener extends JobChangeAdapter {
	
	private static final ReentrantLock classLock = new ReentrantLock();
		
	private int pendingJobs;
	private List<TreeObject> uiResults;
	private SearchResultsView searchResultsView;
	
	public SearchJobListener(SearchResultsView searchResultsView, int numberOfJobs) {
		uiResults = new ArrayList<TreeObject>();
		this.searchResultsView = searchResultsView;
		pendingJobs = numberOfJobs;
	}
	
	public void done(IJobChangeEvent event) {
		Job job = event.getJob();
		
		if(job instanceof SearchJob) {
			
			SearchJob searchJob = (SearchJob)job;
			
			if(event.getResult().isOK()) {
				//Save all results...
				uiResults.addAll(searchJob.getUiResults());            
			}
			
			//synch...
			classLock.lock();
			
			//Update counter...
			pendingJobs--;
			
			//unsynch
			classLock.unlock();   
			
			if(pendingJobs == 0) {
				
				//Update this...
				SearchController.setHasFoundResults(!uiResults.isEmpty());
				
				//Asynch Update UI...
				Display.getDefault().asyncExec(new Runnable () {
					
					public void run() {
						
						//Update the UI components...
						SearchResultsContentProvider contentProvider = 
							(SearchResultsContentProvider)
							searchResultsView.getSearchResultsTreeViewer().getContentProvider();
						
						//Update the content...
						contentProvider.setContent(uiResults);    
						
						//Update the controls...
						searchResultsView.updateSearchResultsControls();
					}
				}); 
			} 
		}
	}
}