import java.awt.Point;
import java.util.*;

import org.w3c.dom.*;


/*
 * Describes a Place in a Place/Transition Petri Net
 */
public class PNPlace {
	public boolean HasToken = false;
	public final boolean InitiallyMarked;
	public final String Id;
	public final Point Position;

	public final int Radius = 11;
	
	private final Element domElem;
	
	
	
	public PNPlace(Element xmlDomElement) {
		domElem = xmlDomElement;
		if(!domElem.getNodeName().equals("place")) 
			throw new RuntimeException("PNPlace constructor called, but not a <place> element: " + domElem);
		Id = domElem.getAttribute("id");
		NodeList marking = domElem.getElementsByTagName("initialMarking");
		if(marking.getLength() > 0 && marking.item(0).getChildNodes().getLength() > 0) {
			Element e = (Element)marking.item(0);
			NodeList textElem = e.getElementsByTagName("text");
			if(textElem.getLength() > 0)
				HasToken = Integer.parseInt(((Element)textElem.item(0)).getFirstChild().getNodeValue()) > 0;
			else
				HasToken = Integer.parseInt(marking.item(0).getFirstChild().getNodeValue()) > 0;
		}
		InitiallyMarked = HasToken;
		Element gfx = null;
		try{
			NodeList ch = domElem.getChildNodes();
			for(int i=0; i<ch.getLength(); i++)
				if(!("graphics").equals(ch.item(i).getNodeName()))
					continue;
				else {
					gfx = (Element)ch.item(i);
					break;
				}
			if(gfx == null)
				throw new Exception();
			//gfx = (Element)domElem.getElementsByTagName("graphics").item(0);
		}catch(Throwable t){
			throw new RuntimeException("Required tag <graphics> not found.");
		}
		Position = PnmlData.getPointsFromGraphics(gfx)[0];
	}

	public boolean isClick(Point pos){
		double dx = pos.x - Position.x;
		double dy = pos.y - Position.y;
		if(Math.sqrt(dx*dx+dy*dy) < Radius)
			return true;
		return false;
	}
	
	@Override
	public String toString() {
		return "PNPlace [HasToken=" + HasToken + ", Id=" + Id + ", Position="
				+ Position + "]";
	}
	
}
