/**
 * $id:  $
 */
package org.jvnet.lookout.ui.core.tree.filter.item;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerFilter;
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;

public class SourceFilter extends ViewerFilter {

	private List<SearchResultSource> visibleSources;
	
	public SourceFilter() {
		super();		
		visibleSources = new ArrayList<SearchResultSource>(2);
		
		synchWithUserPreferences();
	}
	
	@Override
	public boolean select(Viewer viewer, Object parentElement, Object element) {
		
		if(element instanceof SearchResultItem) {			
			return checkIfItemIsVisible((SearchResultItem)element);
		} else {
			//Should not filter anything else... 
			return true;
		}
	}
	
	public void setSourceVisible(SearchResultSource source, boolean visible) {
		if(visible && !visibleSources.contains(source)) {
			visibleSources.add(source);
		} else if(!visible && visibleSources.contains(source)) {
			visibleSources.remove(source);
		}
	}

	private boolean checkIfItemIsVisible(SearchResultItem item) {		
		return visibleSources.contains(item.getPropertyValue(SearchResultProperty.SOURCE));		
	}
	
	public void synchWithUserPreferences() {
		//CXB Could provide this as a preference
		Collection<SearchAdapter> adapters = org.jvnet.lookout.core.Plugin.getDefault().getSearchAdapters();
		
		for (SearchAdapter adapter : adapters) {
			setSourceVisible(adapter.getSearchResultSource(), true);
		}
		
	}

}
