package psplot;

import real.*;

public class ConvexPolygon {
	// convex hull of half planes Ax + By <= C
	public RealLine ell[];
	
	public ConvexPolygon(RealLine m[]) {
		ell = m;
	}
	
	public ConvexPolygon(RealPolygon p) {
		int n = p.b.length;
		ell = new RealLine[n];
		RealPoint Q = p.b[n-1];
		for (int i=0;i<n;i++) {
			RealPoint P = p.b[i];
			double A = P.y - Q.y, B = Q.x - P.x, C = A*P.x + B*P.y;
			ell[i] = new RealLine(A, B, C);
			Q = P;
		}
	}
	
	public ConvexPolygon(RealPoint b[]) {
		int n = b.length;
		// System.out.println("n = " + n);
		ell = new RealLine[n];
		RealPoint Q = b[n-1];
		for (int i=0;i<n;i++) {
			RealPoint P = b[i];
			/* System.out.println("P = " + P);
			System.out.println("Q = " + Q); */
			double A = P.y - Q.y, B = Q.x - P.x, C = A*P.x + B*P.y;
			ell[i] = new RealLine(A, B, C);
			Q = P;
		}
	}
	
	public boolean contains(RealPoint P) {
		boolean ok = true;
		int i = 0;
		while (i < ell.length && ok) {
			RealLine m = ell[i];
			ok &= ((m.A*P.x + m.B*P.y) <= m.C);
			i++;
		}
		return(ok);
	}
	
	// returns point where line from P to Q meets rectangle R
	// P known to be inside our polygon
	public RealPoint clipEnd(RealPoint P, RealPoint Q) {
		RealPoint S = new RealPoint(Q.x, Q.y);
		for (int i=0;i<ell.length;i++) {
			double A = ell[i].A;
			double B = ell[i].B;
			double C = ell[i].C;
			double c = A*S.x + B*S.y;
			double d = A*P.x + B*P.y;
			if (C < c) {
				// S outside 
				double t = (C-d)/(c-d);
				S = RealPoint.interpolate(t, P, S);
			}
		}
		return(S);
	}
	
	public String toString() {
		StringBuffer sb = new StringBuffer();
		for (int i=0;i<ell.length;i++) {
			sb.append(ell[i].A + " + " + ell[i].B + " = " + ell[i].C + '\n');
		}
		return(new String(sb));
	}
}