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

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

import org.eclipse.jface.viewers.Viewer;
import org.jvnet.lookout.core.model.SearchResultProperty;
import org.jvnet.lookout.ui.core.tree.SearchResultDetail;
import org.jvnet.lookout.ui.core.tree.sort.SearchResultDetailSorter;

/**
 * <code>DefaultDetailSorter</code> sort the details in one large category the
 * details in this order:
 * 
 * <ol>
 * <li>URL</li>
 * <li>Snippet</li>
 * </ol>
 * 
 * <p>
 * @author Cleo Barretto
 *
 */
public class DefaultDetailSorter implements SearchResultDetailSorter {
 
    private Map<SearchResultProperty, Integer> propertyToIndex;
    
    public DefaultDetailSorter() {
        propertyToIndex = new HashMap<SearchResultProperty, Integer>(15);
        
        updateIndex();
    }
    
    /**
     * See class description for default sort order.
     * 
     * @see org.jvnet.lookout.ui.core.tree.sort.SearchResultDetailSorter#compare(org.eclipse.jface.viewers.Viewer, org.jvnet.lookout.ui.core.tree.SearchResultDetail, org.jvnet.lookout.ui.core.tree.SearchResultDetail)
     */
    public int compare(Viewer viewer, SearchResultDetail detail1, SearchResultDetail detail2) {
        
        SearchResultProperty property1 = detail1.getProperty();
        SearchResultProperty property2 = detail2.getProperty();
        
        int index1 = getSearchResultPropertySortIndex(property1);
        int index2 = getSearchResultPropertySortIndex(property2);
        
        return index1 - index2;
    }

    /**
     * All details default to one category.
     * 
     * @see org.jvnet.lookout.ui.core.tree.sort.SearchResultDetailSorter#category(org.jvnet.lookout.ui.core.tree.SearchResultDetail)
     */
    public int category(SearchResultDetail detail) {
        return 0;
    }

    public void setSearchResultPropertySortIndex(SearchResultProperty property, int index) {
        propertyToIndex.put(property, index);
    }

    /**
     * Returns -1 if this provided property is not indexed.
     * @param property
     * @return
     */
    public int getSearchResultPropertySortIndex(SearchResultProperty property) {
        Integer index = propertyToIndex.get(property);
        return (null == index) ? -1: index.intValue();
    }

    public void updateIndex() {
        //CXB Ideally would look at preferences to find out the new 
    	//indices for the properties
        
        int i = 0;
        
        setSearchResultPropertySortIndex(SearchResultProperty.URL, i++);
        setSearchResultPropertySortIndex(SearchResultProperty.SNIPPET, i++);        
    }
}
