package hiro.yoshioka.sql.notes.reflect;

import hiro.yoshioka.classmanager.ClassManager;
import hiro.yoshioka.sql.resource.notes.ItemType;
import hiro.yoshioka.util.StringUtil;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Vector;

public class WolfItem extends AbsWolfDominoReflection {
	/*  */
	public static int RTELEM_TYPE_TEXTPARAGRAPH = 0x4;
	public static int RTELEM_TYPE_DOCLINK = 0x5;
	public static int RTELEM_TYPE_FILEATTACHMENT = 0x8;
	public static int RTELEM_TYPE_OLE = 0x9;
	public static int RTELEM_TYPE_SECTION = 0x6;
	public static int RTELEM_TYPE_TABLE = 0x1;
	public static int RTELEM_TYPE_TABLECELL = 0x7;
	public static int RTELEM_TYPE_TEXTPOSITION = 0xa;
	public static int RTELEM_TYPE_TEXTRUN = 0x3;
	public static int RTELEM_TYPE_TEXTSTRING = 0xb;
	private static final String[] IGNORE_RICHTEXT_ITEMS = { "$Fonts" };
	/*  */
	Method getName;
	Method getType;
	Class richTextItemClass;
	Method getEmbeddedObjects;
	Method createRange;
	Method createNavigator;

	public WolfItem(ClassManager classManager, Object instance)
			throws MalformedURLException, ClassNotFoundException,
			SecurityException, NoSuchMethodException {
		super(classManager, instance);
		// lotus.domino.ACLEntry
		// wolf_acl_entry = new WolfACLEntry(classManager);
		getName = targetInstance.getClass().getMethod("getName");
		getType = targetInstance.getClass().getMethod("getType");
		// lotus.domino.RichTextItem
		richTextItemClass = classManager
				.getClassForName("lotus.domino.RichTextItem");
		getEmbeddedObjects = richTextItemClass.getMethod("getEmbeddedObjects");
		createRange = richTextItemClass.getMethod("createRange");
		createNavigator = richTextItemClass.getMethod("createNavigator");
	}

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

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

	public WolfRichTextRange createRange() throws IllegalArgumentException,
			IllegalAccessException, InvocationTargetException,
			MalformedURLException, SecurityException, ClassNotFoundException,
			NoSuchMethodException {
		Object instance = createRange.invoke(targetInstance);
		if (instance == null) {
			return null;
		}

		return new WolfRichTextRange(classManager, instance);

	}

	public WolfRichTextNavigator createNavigator()
			throws IllegalArgumentException, IllegalAccessException,
			InvocationTargetException, MalformedURLException,
			SecurityException, ClassNotFoundException, NoSuchMethodException {
		Object instance = createNavigator.invoke(targetInstance);
		if (instance == null) {
			return null;
		}

		return new WolfRichTextNavigator(classManager, instance);

	}

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

	public List<WolfEmbeddedObject> getEmbeddedObjects()
			throws IllegalArgumentException, IllegalAccessException,
			InvocationTargetException, MalformedURLException,
			SecurityException, ClassNotFoundException, NoSuchMethodException {
		Vector instance = (Vector) getEmbeddedObjects.invoke(targetInstance);
		if (instance == null) {
			return Collections.EMPTY_LIST;
		}
		List<WolfEmbeddedObject> retList = new ArrayList<WolfEmbeddedObject>();
		for (Object o : instance) {
			retList.add(new WolfEmbeddedObject(classManager, o));
		}

		return retList;
	}

	public List<File> saveAttachment(File outDir) throws Exception {
		List<File> ret = null;
		try {
			for (WolfEmbeddedObject obj : getEmbeddedObjects()) {
				if (obj.getType() == WolfEmbeddedObject.EMBED_ATTACHMENT) {
					outDir.mkdirs();
					File to = new File(outDir, obj.getSource().replaceAll(
							StringUtil.TAB_STRING, StringUtil.EMPTY_STRING));
					obj.extractFile(to.getAbsolutePath());
					if (to.exists()) {
						if (ret == null) {
							ret = new ArrayList<File>();
						}
						ret.add(to);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ret;
	}

	@Override
	public String toString() {
		try {
			return String.format("WolfItem %s [%s]", getName(), getType()
					.name());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "WolfItem";
	}

	public static boolean isIgnoreItem(String name) {
		for (String s : IGNORE_RICHTEXT_ITEMS) {
			if (s.equals(name)) {
				return true;
			}
		}
		return false;
	}

	public boolean isIgnoreItem() {
		for (String s : IGNORE_RICHTEXT_ITEMS) {
			try {
				if (s.equals(this.getName())) {
					return true;
				}
			} catch (Exception e) {
			}
		}
		return false;
	}

	public boolean isRichText() throws IllegalArgumentException,
			IllegalAccessException, InvocationTargetException {
		return ItemType.RICHTEXT.equals(getType());
	}

	public String getRichText2HtmlStringByDxl() {
		StringBuilder buf = new StringBuilder();
		try {
			WolfRichTextNavigator rtnav = createNavigator();
			WolfRichTextRange range = createRange();
			if (rtnav.findFirstElement(WolfItem.RTELEM_TYPE_TEXTRUN)) {
				do {
					range.setBegin(rtnav);
					rtnav.setPositionAtEnd();
					range.setEnd(rtnav);

					WolfRichTextStyle style = range.getStyle();

					buf.append(style.getRichText2HtmlString(range.getTextRun()));
					// WolfRichTextStyle style = range.getStyle();
				} while (rtnav.findNextElement(WolfItem.RTELEM_TYPE_TEXTRUN));
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return buf.toString();
	}

	public String getRichText2HtmlString() {
		StringBuilder buf = new StringBuilder();
		try {
			WolfRichTextNavigator rtnav = createNavigator();
			WolfRichTextRange range = createRange();
			if (rtnav.findFirstElement(WolfItem.RTELEM_TYPE_TEXTRUN)) {
				do {
					System.err.println("RTELEM_TYPE_TEXTPARAGRAPH=");
					range.setBegin(rtnav);
					rtnav.setPositionAtEnd();
					range.setEnd(rtnav);

					WolfRichTextStyle style = range.getStyle();

					buf.append(style.getRichText2HtmlString(range.getTextRun()));
					// WolfRichTextStyle style = range.getStyle();
				} while (rtnav.findNextElement(WolfItem.RTELEM_TYPE_TEXTRUN));
			}
			// if (rtnav.findFirstElement(WolfItem.RTELEM_TYPE_FILEATTACHMENT))
			// {
			// do {
			// WolfEmbeddedObject obj = rtnav.getEmbeddedElement();
			// File ff = new File("C:/tmp/hogehoge.txt");
			// obj.extractFile(ff.getAbsolutePath());
			// System.err.println("RTELEM_TYPE_FILEATTACHMENT=" + ff);
			// } while (rtnav
			// .findNextElement(WolfItem.RTELEM_TYPE_FILEATTACHMENT));
			// }
			if (rtnav.findFirstElement(WolfItem.RTELEM_TYPE_DOCLINK)) {
				do {
					System.err.println("RTELEM_TYPE_DOCLINK=");
				} while (rtnav.findNextElement(WolfItem.RTELEM_TYPE_DOCLINK));
			}
			if (rtnav.findFirstElement(WolfItem.RTELEM_TYPE_OLE)) {
				do {
					System.err.println("RTELEM_TYPE_OLE=");
				} while (rtnav.findNextElement(WolfItem.RTELEM_TYPE_OLE));
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return buf.toString();
	}
}
