package rpn.graphics;

import java.util.Stack;
import java.awt.*;

import plots.*;

public class CalculatorCanvas extends PlotCanvas {
	int[] currentPoint = null;
	int[] lastMove = null;
	Stack polyStack;
	int[] cX = new int[2048], cY = new int[2048];
	int N;
	float llx, urx, lly, ury;
	
	public CalculatorCanvas(int w, int h) {
		super(w, h);
		setDimensions(w, h);
	}

	// don't want to draw until paint is called

	public void draw() {
	}

	// --- drawing items ------------------------------

	public void newpath() {
		polyStack = new Stack();
		currentPoint = null;
		N = 0;
	}

	public void moveto(double x, double y) {
		int[] p = matrix.transform((float) x, (float) y);
		if (N > 0) {
			Polygon poly = new Polygon(cX, cY, N);
			polyStack.push(poly);
		}
		currentPoint = p;
		lastMove = p;
		cX[0] = p[0]; cY[0] = p[1];
		N = 1;
	}

	public void lineto(double x, double y) throws NoCurrentPointException  {
		if (currentPoint != null) {
			int[] p = matrix.transform((float) x, (float) y);
			gfx.drawLine(currentPoint[0], currentPoint[1], p[0], p[1]);
			currentPoint = p;
			cX[N] = p[0]; cY[N++] = p[1];
		} else throw new NoCurrentPointException();
	}

	public void fill() {
		Polygon poly= new Polygon(cX, cY, N);
		polyStack.push(poly);
		for (int i=0;i<polyStack.size();i++) {
			gfx.fillPolygon((Polygon) polyStack.elementAt(i));
		}
	}

	public void stroke() {
		Polygon poly= new Polygon(cX, cY, N);
		polyStack.push(poly);
		for (int i=0;i<polyStack.size();i++) {
			gfx.drawPolygon((Polygon) polyStack.elementAt(i));
		}
	}

	public void pixel(double x, double y) {
		int[] p = matrix.transform((float) x, (float) y);
		gfx.fillRect(p[0] - 1, p[1] - 1, 3, 3);
	}

	// --- changing coordinates ------------------------

	public void rotate(double x) {
		matrix.rotate((float) x);
	}

	public void translate(double x, double y) {
		matrix.translate((float) x, (float) y);
	}

	public void scale(double x, double y) {
		matrix.scale((float) x, (float) y);
	}

	public void setDimensions(int w, int h) {
		llx = -(float) w/144.0f; urx = llx + w/72.0f; lly = ((float) h/(float) w)*llx; ury = -lly;
		matrix.setCorners(llx, lly, urx, ury);
	}

	// --- other graphics items --------------------------

	public void setColor(float r, float g, float b) {
		gfx.setColor(new Color(r, g, b));
	}

	public void paint() {
		getGraphics().drawImage(img, 0, 0, null);
	}

	public void reset() {
		matrix.setCorners(llx, lly, urx, ury);
		clear();
		paint();
	}
}	