package plots;

import java.awt.Image;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Polygon;
import java.applet.Applet;

public class BackgroundCanvas {
	public Matrix2d matrix;
	public Graphics gfx;
	int x, y;
	PlotCanvas target;
	Image img;
	Color fg = Color.black, bg = Color.white;
	
	// matrix equals ac's
	public BackgroundCanvas(PlotCanvas ac, int w, int h) {
		target = ac;
		this.x = 0;
		this.y = 0;
		matrix = ac.matrix;
	}

	// makes a new copy
	public BackgroundCanvas(PlotCanvas ac,
			int x, int y, int w, int h) {
		target = ac;
		this.x = x;
		this.y = y;
		matrix = new Matrix2d(w, h);
		matrix.m = new float[6];
		for (int i=0;i<6;i++) {
			matrix.m[i] = ac.matrix.m[i];
		}
		matrix.m[4] -= x;
		matrix.m[5] -= y;
	}
	
	public void addNotify() {
		img = target.createImage(matrix.w, matrix.h);
		gfx = img.getGraphics();
	}
	
	public void render() {
		target.gfx.drawImage(img, x, y, null);
	}
	
	public void clear() {
		gfx.setColor(bg);
		gfx.fillRect(0, 0, matrix.w, matrix.h);
		gfx.setColor(fg);
	}
	
	public void drawLine(float x0, float y0, float x1, float y1, Color c) {
		int p[] = matrix.transform(x0, y0);
		int q[] = matrix.transform(x1, y1);
		gfx.setColor(c);
		gfx.drawLine(p[0], p[1], q[0], q[1]);
	}
	
	public void drawPolygon(Polygon p, Color c) {
		gfx.setColor(c);
		int x[] = p.xpoints, y[] = p.ypoints;
		for (int i=1;i<p.npoints;i++) {
			// System.err.println("x, y = " + x[i] + ", " + y[i]);
			gfx.drawLine(x[i-1], y[i-1], x[i], y[i]);
		}
	}
	
	public void fillPolygon(Polygon p, Color c) {
		gfx.setColor(c);
		gfx.fillPolygon(p);
	}

}
