package hiro.yoshioka.sql;

import hiro.yoshioka.sql.resource.DBConstraintRoot;
import hiro.yoshioka.sql.resource.DBDictionaryRoot;
import hiro.yoshioka.sql.resource.DBIndexRoot;
import hiro.yoshioka.sql.resource.IDBColumn;
import hiro.yoshioka.sql.resource.IDBSchema;
import hiro.yoshioka.sql.resource.IDBSequence;
import hiro.yoshioka.sql.resource.IDBTable;
import hiro.yoshioka.sql.resource.IDBTrigger;
import hiro.yoshioka.sql.resource.RecentryUsedResource;
import hiro.yoshioka.sql.resource.notes.NotesDBSchema;
import hiro.yoshioka.util.StringUtil;

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

public class ResourceSorter extends ViewerSorter {
	public static int SORT_NOTHING = 0;

	public static int SORT_CATEGORY = 1;

	private int imode = SORT_NOTHING;

	public void sort(final Viewer viewer, Object[] elements) {
		if (imode == SORT_CATEGORY) {
			super.sort(viewer, elements);
		}
	}

	@Override
	public int compare(Viewer viewer, Object e1, Object e2) {
		if (e1 instanceof NotesDBSchema && e2 instanceof NotesDBSchema) {
			NotesDBSchema n1 = (NotesDBSchema) e1;
			NotesDBSchema n2 = (NotesDBSchema) e2;
			String s1 = StringUtil.EMPTY_STRING;
			String s2 = StringUtil.EMPTY_STRING;
			if (n1 != null) {
				s1 = StringUtil.nvl(n1.getProperties().getProperty("filePath"));
			}
			if (n2 != null) {
				s2 = StringUtil.nvl(n1.getProperties().getProperty("filePath"));
			}
			return s1.compareTo(s2);
		}
		return super.compare(viewer, e1, e2);
	}

	public int category(Object element) {
		return sort_category(element);
	}

	private int sort_category(Object element) {
		if (element instanceof DBIndexRoot) {
			return 10;
		}
		if (element instanceof DBDictionaryRoot) {
			return 15;
		}
		if (element instanceof DBConstraintRoot) {
			return 20;
		}
		if (element instanceof IDBTable) {
			IDBTable table = (IDBTable) element;
			if (table.isTable()) {
				return 105;
			} else if (table.isView()) {
				return 110;
			} else if (table.isFunction()) {
				return 115;
			} else if (table.isProcudeure()) {
				return 120;
			}
			return 125;
		} else if (element instanceof RecentryUsedResource) {
			return 80;
		} else if (element instanceof IDBSchema) {
			return 85;
		}
		if (element instanceof IDBTrigger) {
			return 140;
		}
		if (element instanceof IDBSequence) {
			return 130;
		}

		if (element instanceof IDBColumn) {
			if (((IDBColumn) element).isPkey()) {
				return 50;
			} else if (((IDBColumn) element).isNotNull()) {
				return 55;
			} else {
				return 58;
			}
		}
		return 100;
	}

	public void setMode(int mode) {
		imode = mode;
	}

	// public int compare(Viewer arg0, Object arg1, Object arg2) {
	// return
	// ((DBResource)arg1).getName().compareTo(((DBResource)arg2).getName());
	// }

}