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

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;

import com.thoughtworks.xstream.annotations.XStreamAsAttribute;

/**
 * フォルダ
 * @author iwasaki
 */
public class BeansFolder {
	
	@XStreamAsAttribute
	private String name=null;
	private ArrayList<BeanClass> classes=null;
	private ArrayList<BeansFolder> subFolders=null;
	private transient BeansFolder parentFolder=null;
	
	public BeansFolder(String name) {
		this.name = name;
	}

	public String getName() {
		return name;
	}

	public Collection<BeanClass> classes() {
		if (classes==null) classes=new ArrayList<BeanClass>();
		return classes;
	}

	public Collection<BeansFolder> subFolders() {
		if (subFolders==null) subFolders=new ArrayList<BeansFolder>();
		return subFolders;
	}

	public BeansFolder getParentFolder() {
		return parentFolder;
	}

	public void setParentFolder(BeansFolder parentFolder) {
		this.parentFolder = parentFolder;
	}
	
	public String getLabel() {
		return name;
	}

	public void afterLoad() {
		
		if (classes!=null) {
			Collections.sort(classes, new Comparator<BeanClass>() {
				@Override
				public int compare(BeanClass o1, BeanClass o2) {
					return o1.getLabel().compareTo(o2.getLabel());
				}
			});
			for(BeanClass c: classes) {
				c.setParentFolder(this);
			}
		}
		if (subFolders!=null) {
			Collections.sort(subFolders, new Comparator<BeansFolder>() {
				@Override
				public int compare(BeansFolder o1, BeansFolder o2) {
					return o1.getLabel().compareTo(o2.getLabel());
				}
			});
			for(BeansFolder f: subFolders) {
				f.setParentFolder(this);
				f.afterLoad();
			}
		}
	}

	public boolean hasChildrenForSearcher(StringSearcher searcher) {
		for(BeansFolder f:subFolders()) {
			if (f.hasChildrenForSearcher(searcher)) return true;
		}
		for(BeanClass c:classes()) {
			if (c.matchToSearcher(searcher)) return true;
		}
		return false;
	}

	public void getChildrenForSearcher(Collection<Object> li, StringSearcher searcher) {
		for(BeansFolder f:subFolders()) {
			if (f.hasChildrenForSearcher(searcher)) li.add(f);
		}
		for(BeanClass c:classes()) {
			if (c.matchToSearcher(searcher)) li.add(c);
		}
	}
}
