package plots;

import java.awt.Polygon;
import java.awt.Graphics;
import java.awt.Color;

public class ActiveRectangle {
	public int w, h;
	// centre
	float c[];
	// from corner to centre	
	Matrix2d m;

	// cx, cy = centre
	public ActiveRectangle(Matrix2d m, float cx, float cy, float w, float h) {
		this.m = m;
		int[] ul = m.transform(cx - w/2, cy - h/2);
		int[] lr = m.transform(ul[0] + w, ul[1] + h);
		this.w = lr[0] - ul[0];
		this.h = lr[1] - ul[1];
		c = new float[2];
		c[0] = cx; c[1] = cy;
	}

	// cx, cy = centre
	public ActiveRectangle(Matrix2d m, float cx, float cy, int w, int h) {
		this.m = m;
		this.w = w;
		this.h = h;
		c = new float[2];
		c[0] = cx; c[1] = cy;
	}
	
	public float[] getCentre() {
		return(c);
	}
	
	public void setCentre(float x, float y) {
		c[0] = x; c[1] = y;
	}
	
	public boolean contains(int x, int y) {
		int p[] = m.transform(c[0], c[1]);
		x -= p[0]; if (x < 0) x = -x;
		y -= p[1]; if (y < 0) y = -y;
		return(x <= w/2 && y <= h/2);
	}
	
	public Polygon boundary(Matrix2d m) {
		int[] x= new int[5], y = new int[5];
		int[] p = m.transform(c[0], c[1]);
		x[0] = p[0] - w/2;
		y[0] = p[1] - h/2;
		x[1] = x[0];
		y[1] = y[0] + h;
		x[2] = x[1] + w;
		y[2] = y[1];
		x[3] = x[2];
		y[3] = y[2] - h;
		x[4] = x[0];
		y[4] = y[0];
		return(new Polygon(x, y, 5));
	}

	public void draw(Graphics gfx, Color col) {
		int[] p = m.transform(c[0], c[1]);
		gfx.setColor(col);
		gfx.drawRect(p[0] - w/2, p[1] - h/2, w, h);
	}

	public void fill(Graphics gfx, Color col) {
		int[] p = m.transform(c[0], c[1]);
		gfx.setColor(col);
		gfx.fillRect(p[0] - w/2, p[1] - h/2, w, h);
	}
}
