package hiro.yoshioka.sql.notes.reflect;

import hiro.yoshioka.classmanager.ClassManager;
import hiro.yoshioka.sql.resource.INameFamily;
import hiro.yoshioka.sql.resource.notes.ItemType;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.util.Vector;

public class WolfForm extends AbsWolfDominoReflection {
	Method getName;
	Method getReaders;
	Method getAliases;
	Method getFields;
	Method getFieldType;
	Method recycle;

	public WolfForm(ClassManager classManager, Object targetInstance)
			throws MalformedURLException, ClassNotFoundException,
			SecurityException, NoSuchMethodException {
		super(classManager, targetInstance);

		getName = targetInstance.getClass().getMethod("getName");
		getReaders = targetInstance.getClass().getMethod("getReaders");
		getAliases = targetInstance.getClass().getMethod("getAliases");
		getFields = targetInstance.getClass().getMethod("getFields");
		getFieldType = targetInstance.getClass().getMethod("getFieldType",
				String.class);
	}

	public boolean isThisForm(INameFamily name)
			throws IllegalArgumentException, IllegalAccessException,
			InvocationTargetException {
		if (name == null) {
			return false;
		}
		if (getName().equals(name.getName())) {
			return true;
		}
		if (getName().equals(name.getAlias())) {
			return true;
		}
		for (String alias : getAliases()) {
			if (alias.equals(name.getName())) {
				return true;
			}
			if (alias.equals(name.getAlias())) {
				return true;
			}
		}
		return false;
	}

	@Override
	public String getDominoClassName() {
		return "lotus.domino.Form";
	}

	public String getName() throws IllegalArgumentException,
			IllegalAccessException, InvocationTargetException {
		return (String) getName.invoke(targetInstance);
	}

	public Vector<String> getReaders() throws IllegalArgumentException,
			IllegalAccessException, InvocationTargetException {
		return (Vector<String>) getReaders.invoke(targetInstance);
	}

	public Vector<String> getAliases() throws IllegalArgumentException,
			IllegalAccessException, InvocationTargetException {
		return (Vector<String>) getAliases.invoke(targetInstance);
	}

	public Vector<String> getFields() throws IllegalArgumentException,
			IllegalAccessException, InvocationTargetException {
		return (Vector<String>) getFields.invoke(targetInstance);
	}

	public ItemType getFieldType(String fieldName)
			throws IllegalArgumentException, IllegalAccessException,
			InvocationTargetException {
		return ItemType.parse((Integer) getFieldType.invoke(targetInstance,
				fieldName));
	}

	@Override
	public String toString() {
		StringBuilder buf = new StringBuilder();
		try {
			buf.append(String.format("WolfForm %s%n", getName()));

		} catch (Exception e) {
			e.printStackTrace();
		}
		return buf.toString();
	}
}
