package hiro.yoshioka.sql.resource.view;

import hiro.yoshioka.sql.params.ConnectionProperties;
import hiro.yoshioka.sql.resource.DBResource;
import hiro.yoshioka.sql.resource.DBRoot;
import hiro.yoshioka.sql.resource.IDBResource;

import java.util.AbstractCollection;

import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.widgets.TreeItem;

public class DBTreeContentProvider implements ITreeContentProvider {

	DBResource[] ZERO_RESOURCE_ARRAY = new DBResource[0];

	public DBTreeContentProvider() {
	}

	public Object[] getChildren(Object element) {
		if (element instanceof AbstractCollection) {
			AbstractCollection<ConnectionProperties> s = (AbstractCollection<ConnectionProperties>) element;
			return s.toArray(new ConnectionProperties[s.size()]);
		} else if (element instanceof ConnectionProperties) {
			ConnectionProperties prop = (ConnectionProperties) element;
			if (prop.getDBRootResource() == null) {
				return ZERO_RESOURCE_ARRAY;
			}
			return new IDBResource[] { prop.getDBRootResource() };
		} else if (element instanceof DBRoot) {
			DBRoot root = (DBRoot) element;
			Object[] kids = root.listArrayResourcesWithMisc();
			return kids == null ? new Object[0] : kids;
		} else {
			Object[] kids = ((IDBResource) element).listArrayResources();
			return kids == null ? new Object[0] : kids;
		}
	}

	public Object[] getElements(Object element) {
		return getChildren(element);

	}

	public boolean hasChildren(Object element) {
		Object[] ret = getChildren(element);
		if (ret == null || ret.length == 0) {
			return false;
		}
		return true;
	}

	public Object getParent(Object element) {
		if (element instanceof TreeItem) {
			Object o = ((TreeItem) element).getData();
			if (o instanceof ConnectionProperties) {
				return null;
			} else {
				System.out.println("kkkkkkkkkkk");
				return ((IDBResource) o).getParent();
			}
		}
		if (element instanceof ConnectionProperties) {
			return null;
		} else {
			return ((IDBResource) element).getParent();
		}
	}

	public void dispose() {
	}

	public void inputChanged(Viewer viewer, Object old_input, Object new_input) {

	}

}