package hiro.yoshioka.sql.resource;

import java.sql.DatabaseMetaData;
import java.util.Iterator;
import java.util.TreeSet;

public class DBCrossRefference extends DBResource {
	private static final long serialVersionUID = 999962784216L;
	public TreeSet<IDBColumn> pkList = new TreeSet<IDBColumn>();
	public TreeSet<IDBColumn> fkList = new TreeSet<IDBColumn>();
	private int updateRule;
	private int deleteRule;

	public DBCrossRefference(DBIndexRoot root) {
		super(root);
	}

	public void putPkColumn(IDBColumn column) {
		pkList.add(column);
	}

	public void putFkColumn(IDBColumn column) {
		fkList.add(column);
	}

	@Override
	public void putResource(String key, IDBResource child) {
		throw new RuntimeException("use putFkColumn method");
	}

	boolean isPk(IDBColumn column) {
		for (Iterator<IDBColumn> ite = pkList.iterator(); ite.hasNext();) {
			IDBColumn col = ite.next();
			if (col.getName().equals(column.getName())
					&& col.getParent().getName().equals(
							column.getParent().getName())) {
				return true;
			}
		}
		return false;
	}

	public boolean contain(String pattern) {
		if (containKeyInNameOrComment(pattern.toUpperCase())) {
			return true;
		}
		for (Iterator ite = listResources().iterator(); ite.hasNext();) {
			if (((IDBColumn) ite.next()).contain(pattern)) {
				return true;
			}
		}

		return false;
	}

	public void setUpdateRule(int rule) {
		this.updateRule = rule;
	}

	public void setDeleteRule(int rule) {
		this.deleteRule = rule;
	}

	public String getDeleteRuleString() {
		switch (deleteRule) {
		case DatabaseMetaData.importedKeyNoAction:
			return "importedKeyNoAction";
		case DatabaseMetaData.importedKeyCascade:
			return "importedKeyCascade";
		case DatabaseMetaData.importedKeySetNull:
			return "importedKeySetNull";
		case DatabaseMetaData.importedKeySetDefault:
			return "importedKeySetDefault";
		case DatabaseMetaData.importedKeyRestrict:
			return "importedKeyRestrict";

		default:
			return "unKnown";
		}
	}

	public String getUpdateRuleString() {
		switch (updateRule) {
		case DatabaseMetaData.importedKeyNoAction:
			return "importedKeyNoAction";
		case DatabaseMetaData.importedKeyCascade:
			return "importedKeyCascade";
		case DatabaseMetaData.importedKeySetNull:
			return "importedKeySetNull";
		case DatabaseMetaData.importedKeySetDefault:
			return "importedKeySetDefault";
		case DatabaseMetaData.importedKeyRestrict:
			return "importedKeyRestrict";

		default:
			return "unKnown";
		}
	}

	public String toString() {
		return name + ":" + pkList + " ⇒" + fkList + " U["
				+ getUpdateRuleString() + "] D[" + getDeleteRuleString() + "]";
	}

	public int getDeleteRule() {
		return deleteRule;
	}

	public int getUpdateRule() {
		return updateRule;
	}
}