package de.ugoe.cs.quest.plugin.mfc.eventcore;

import java.io.ByteArrayInputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import de.ugoe.cs.quest.eventcore.ReplayableEvent;

/**
 * <p>
 * Convenience class for working with Windows MFC events.
 * </p>
 * 
 * @author Steffen Herbold
 * @version 1.0
 */
public class WindowsEvent extends ReplayableEvent<WindowsMessage> {

	/**
	 * <p>
	 * Id for object serialization.
	 * </p>
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * <p>
	 * Constructor. Creates a new WindowEvent.
	 * </p>
	 * 
	 * @see de.ugoe.cs.quest.eventcore.Event#Event(String)
	 * @param type
	 *            type of the event.
	 */
	public WindowsEvent(String type) {
		super(type);
	}

	@Override
	protected boolean targetEquals(String otherTarget) {
		return MFCTargetComparator.compare(target, otherTarget);
	}
	
	int targetHash = 0;
	
	@Override
	protected int targetHashCode() {
		if( targetHash==0 ) {
			int multiplier = 17;
			if (target != null) {
				Document doc;
				try {
					DocumentBuilder documentBuilder = DocumentBuilderFactory
							.newInstance().newDocumentBuilder();
					doc = documentBuilder.parse(new ByteArrayInputStream(
							("<dummy>" + target + "</dummy>").getBytes("UTF-8")));
				} catch (Exception e) {
					e.printStackTrace();
					return 0;
				}
				doc.getDocumentElement().normalize();
				NodeList widgets = doc.getElementsByTagName("window");

				for (int i = 0; i < widgets.getLength(); i++) {
					Element currentWidget = (Element) widgets.item(i);
					targetHash = targetHash* multiplier + widgetHashCode(currentWidget);
				}
			}
		}
		return targetHash;
	}
	
	private int widgetHashCode(Element currentWidget) {
		int hashCode = 0;
		int multiplier = 41;
		hashCode = hashCode * multiplier + currentWidget.getAttribute("class").hashCode();
		hashCode = hashCode * multiplier + currentWidget.getAttribute("resourceId").hashCode();
		hashCode = hashCode * multiplier + currentWidget.getAttribute("isModal").hashCode();
		return hashCode;
	}
}
