package jp.hasc.hasctool.ui.views.beanslist;

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

import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.Viewer;

/**
 * @author iwasaki
 */
public class BeansListContentProvider implements ITreeContentProvider {
	
	private StringSearcher searcher_ = StringSearcher.NULL_SEARCHER;

	@Override
	public void dispose() {
	}

	@Override
	public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
	}

	@Override
	public Object[] getChildren(Object parentElement) {
		if (parentElement instanceof BeansFolder) {
			BeansFolder f = (BeansFolder) parentElement;
			ArrayList<Object> li=new ArrayList<Object>();
			f.getChildrenForSearcher(li,searcher_);
			//li.addAll(f.subFolders());
			//li.addAll(f.classes());
			return li.toArray(new Object[li.size()]);
		}
		return null;
	}

	@Override
	public Object[] getElements(Object inputElement) {
		if (inputElement instanceof Collection<?>) {
			Collection<?> src = ((Collection<?>)inputElement);
			if (searcher_.isEmpty()) {
				return src.toArray();
			}
			
			// filter
			ArrayList<Object> out=new ArrayList<Object>();
			for(Object o:src) {
				if (o instanceof BeansFolder) {
					BeansFolder f = (BeansFolder) o;
					if (!f.hasChildrenForSearcher(searcher_)) continue;
				}else if (o instanceof BeanClass) {
					BeanClass c = (BeanClass) o;
					if (!c.matchToSearcher(searcher_)) continue;
				}
				out.add(o);
			}
			return out.toArray();
		}
		return new Object[0];
	}

	@Override
	public Object getParent(Object element) {
		if (element instanceof BeansFolder) {
			BeansFolder f = (BeansFolder) element;
			return f.getParentFolder();
		}
		if (element instanceof BeanClass) {
			BeanClass c = (BeanClass) element;
			return c.getParentFolder();
		}
		return null;
	}

	@Override
	public boolean hasChildren(Object element) {
		if (element instanceof BeansFolder) {
			BeansFolder f = (BeansFolder) element;
			return f.hasChildrenForSearcher(searcher_);
			//return f.classes().size()>0 || f.subFolders().size()>0;
		}
		return false;
	}

	public StringSearcher getSearcher() {
		return searcher_;
	}

	public void setSearcher(StringSearcher searcher) {
		searcher_ = searcher;
	}


}
