package gve.calc.graph;

import java.awt.*;
import gve.calc.formula.*;

public class GraphMorphismView extends GraphView implements Runnable,View,ActivationListener {
	private GraphMorphism model;
	private Thread animator;
	private boolean stopme = false;

	// Invalidate some GraphView methods
	public void setSize(int size) {}
	public void removeVertex(int idx) {}

	public Object getModel() { return model; }

	public void updateView(Object with) {}

	public GraphMorphismView(GraphMorphism morph) {
		super(morph.graph);
		model = morph;
		int w = VERTEXDIAM*2, h = VERTEXDIAM*2;
		for (int i = morph.map.length - 1; i>=0; i--) {
			if (morph.xcoord1[i]+VERTEXDIAM >= w) w = morph.xcoord1[i]+VERTEXDIAM;
			if (morph.ycoord1[i]+VERTEXDIAM >= h) h = morph.ycoord1[i]+VERTEXDIAM;
			if (morph.xcoord2[i]+VERTEXDIAM >= w) w = morph.xcoord2[i]+VERTEXDIAM;
			if (morph.ycoord2[i]+VERTEXDIAM >= h) h = morph.ycoord2[i]+VERTEXDIAM;
		}
		width = w; height = h;
		int size = model.getSize();
	}

	public void activate() {
		animator = new Thread(this);
		stopme = false;
		animator.start();
	}

	public void deactivate() {
		stopme = true;
	}

	public boolean mousePressed(int flags,int x,int y) { return false; }
	public void mouseDown(int flags,int x,int y) {}

	public void paint(Graphics g) {
		g.drawRect(0,0,width-1,height-1);
		FormulaView view = FormulaView.get(this);
		if (view.getCursorComp() == this) {
			g.drawRect(1,1,width-3,height-3);
		} else {
			Color col = g.getColor();
			g.setColor(Color.gray);
			FontMetrics fm = g.getFontMetrics();
			g.drawString("Click to play",3,3+height-fm.getHeight()+fm.getAscent());
			g.setColor(col);
		}
		paintGraph(g);
	}

	public void run() {
		final float dfraction = 0.04f;
		stopme = false;
		boolean direction = true;	// ascending fractions
		float fraction = 0f;	// 0==graph1, 1==graph2
		while (!stopme) {
			try { Thread.sleep(200); }
			catch (InterruptedException exc) {}
			if (direction) {
				fraction += dfraction;
				if (fraction > 1.5) {
					fraction = 1;
					direction = false;
				}
			} else {
				fraction -= dfraction;
				if (fraction < -0.5) {
					fraction = 0;
					direction = true;
				}
			}
			// calc positions
			float fr = fraction;
			if (fr < 0) fr = 0;
			if (fr > 1) fr = 1;
			Graph graph = model.graph;
			for (int i = graph.getSize()-1; i>=0; i--) {
				graph.setXcoord(i,(int)((1-fr)*model.xcoord1[i] + fr*model.xcoord2[model.map[i]]));
				graph.setYcoord(i,(int)((1-fr)*model.ycoord1[i] + fr*model.ycoord2[model.map[i]]));
			}
			// paint
			repaint(100);
		}
		animator = null;
	}
}