/**
 * Created on Jul 24, 2005
 * $id:  $
 */
package org.jvnet.lookout.ui.core.tree.sort.item;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.eclipse.jface.viewers.Viewer;
import org.jvnet.lookout.core.Plugin;
import org.jvnet.lookout.core.adapter.SearchAdapter;
import org.jvnet.lookout.core.model.SearchResultProperty;
import org.jvnet.lookout.core.model.SearchResultSource;
import org.jvnet.lookout.ui.core.tree.SearchResultItem;
import org.jvnet.lookout.ui.core.tree.sort.SearchResultItemSorter;

public class SourceSorter implements SearchResultItemSorter {
	
	private Map<SearchResultSource, Integer> sourceToIndex;
	
	public SourceSorter() {
		sourceToIndex = new HashMap<SearchResultSource, Integer>(5);
		
		updateIndex();
	}
	
	/**
	 * Does not sort items within each category.
	 * 
	 * @see org.jvnet.lookout.ui.core.tree.sort.SearchResultItemSorter#compare(org.eclipse.jface.viewers.Viewer, org.jvnet.lookout.ui.core.tree.SearchResultItem, org.jvnet.lookout.ui.core.tree.SearchResultItem)
	 */
	public int compare(Viewer viewer, SearchResultItem item1, SearchResultItem item2) {
		return 0;
	}
	
	/**
	 * Categorizes items as defined in the preferences page.
	 * 
	 * @see org.jvnet.lookout.ui.core.tree.sort.SearchResultItemSorter#category(org.jvnet.lookout.ui.core.tree.SearchResultItem)
	 */
	public int category(SearchResultItem item) {
		
		int category;
		
		SearchResultSource itemSource = (SearchResultSource)item.getPropertyValue(SearchResultProperty.SOURCE);
		
		category = getSearchResultSourceSortIndex(itemSource);
		if(category < 0) {
			category = Integer.MAX_VALUE;    
		}
		
		return category;
	}
	
	public void setSearchResultSourceSortIndex(SearchResultSource source, int index) {
		sourceToIndex.put(source, index);
	}
	
	/**
	 * Returns Integer.MAX_VALUE if this provided source is not indexed.
	 * 
	 * @param source
	 * @return
	 */
	public int getSearchResultSourceSortIndex(SearchResultSource source) {
		Integer index = sourceToIndex.get(source);
		return (null == index) ? Integer.MAX_VALUE: index.intValue();
	}
	
	public void updateIndex() {
		List<SearchAdapter> searchAdapters = Plugin.getDefault().getSearchAdapters();
		
		for (SearchAdapter adapter : searchAdapters) {
			sourceToIndex.put(adapter.getSearchResultSource(), searchAdapters.indexOf(adapter));
		}
	}
	
}
