package jp.ac.kyutech.mns.ist;


import java.awt.Color;
import java.awt.Paint;
import java.util.Hashtable;

import javax.swing.JFrame;

import jp.ac.kyutech.mns.ist.util.Util;

import edu.umd.cs.piccolo.PCanvas;
import edu.umd.cs.piccolo.PNode;
import edu.umd.cs.piccolo.event.PBasicInputEventHandler;
import edu.umd.cs.piccolo.event.PInputEvent;
import edu.umd.cs.piccolo.nodes.PPath;
import edu.umd.cs.piccolo.nodes.PText;

/**
 * ATNWindowで右ドラッグしながら青色のズーム範囲矩形を表示し，ズームする機能を実現するクラス
 * @author miuramo
 *
 */
public class InspectorHandler extends PBasicInputEventHandler {

	PNode pressN;
	PInputEvent pressEv = null;
	PCanvas canvas;
	JFrame frame;
	Paint preserveColor = null;
	Hashtable<PNode, Paint> preserve;
	//	public boolean canceled_by_SimpleATN_EnterKey;
	JFrame inspectorFrame = null;
	InspectorPanel inspectorPanel;
	public InspectorHandler(PCanvas _canvas, JFrame _frame) {
		canvas = _canvas;
		frame = _frame;
		preserve = new Hashtable<PNode, Paint>();
		inspectorFrame = Util.createNewFrame_NextTo(frame);
		inspectorPanel = new InspectorPanel(inspectorFrame, this);
		inspectorFrame.getContentPane().add(inspectorPanel);
		inspectorFrame.setTitle("Inspector");
		System.out.println("new Inspector");
	}
	public void mouseMoved(PInputEvent ev){
		pressEv = ev;
		if (pressN == null) setHilit(pressN);
		if (pressN != ev.getPickedNode()){
			resetHilit(pressN);
			pressN = ev.getPickedNode();
			setHilit(pressN);

			showClassName(pressN, 1);
		}
	}
	public void showClassName(PNode p, int level){
		if (level == 1) inspectorPanel.pnlist.clear();
		inspectorPanel.pnlist.add(p);
		String nm = p.getClass().getSimpleName();
		if (level>1) System.out.print(" < ");
		System.out.print(nm);
		PNode parent = p.getParent();
		if (parent != null) showClassName(parent, level+1);
		if (level == 1) System.out.println("");
		inspectorPanel.repaint();
	}
	public void setHilit(PNode n){
		if (n==null) return;
		if (preserve.get(n)==null){
			Paint p = pickColor(n);
			if (p==null) {
//				System.out.println("NULL");
				return;
			}
			preserve.put(n, p);
			for(Object o: n.getAllNodes().toArray()){
				if (o instanceof PNode){
					((PNode)o).setPickable(true);
				}
			}
		}
		hilitColor(n);
	}
	public void resetHilit(PNode n){
		if (n==null) return;
		Paint p = preserve.get(n);
		if (p!=null){
			setColor(n,p);
		}
	}
	public void setColor(PNode n, Paint p){
		if (n instanceof PPath){
			 ((PPath)n).setPaint(p);
		} else if (n instanceof PText){
			 ((PText)n).setTextPaint(p);
		}
	}
	public void hilitColor(PNode n){
		if (n instanceof PPath){
			((PPath)n).setPaint(Color.yellow);
		} else if (n instanceof PText){
			((PText)n).setTextPaint(Color.yellow);
		}
	}
	public Paint pickColor(PNode n){
		if (n instanceof PPath){
			return ((PPath)n).getPaint();
		} else if (n instanceof PText){
			return ((PText)n).getTextPaint();
		}
		return null;
	}

}
