
using System;
using Math2D;

namespace Math2D.Shapes
{
	
	
	public class Polygon2D: Shape2D
	{
		private Vector2D[] FVec;
		
		public Polygon2D() {
			FVec = new Vector2D[3] {
			new Vector2D(),
			new Vector2D(),
			new Vector2D() 
			};
		}
		
		public Polygon2D(Vector2D p0,
		                 Vector2D p1,
		                 Vector2D p2) {
			FVec = new Vector2D[3] {
			p0,
			p1,
			p2 
			};
		}
		
		public Vector2D P1 {
			get { return FVec[0]; }
		}
		
		public Vector2D P2 {
			get { return FVec[1]; }
		}
		
		public Vector2D P3 {
			get { return FVec[2]; }
		}
		
		public Vector2D[] P {
			get { return FVec; }	
		}
		
		public override bool CheckXY (float x, float y) {;
			Vector2D[] p = FVec;
			double d12 = (p[0].X - x) * (p[1].Y - y) - (p[1].X - x) * (p[0].Y - y);
			double d23 = (p[1].X - x) * (p[2].Y - y) - (p[2].X - x) * (p[1].Y - y);
			double d31 = (p[2].X - x) * (p[0].Y - y) - (p[0].X - x) * (p[2].Y - y);
			return (d12 * d23 > 0) & (d23 * d31 > 0);
		}

		public static bool Intersect(Polygon2D b, Polygon2D a) {
			foreach (Vector2D v in a.P) {
				if (b.CheckXY(v.X, v.Y)) return true;
			}
			foreach (Vector2D v in b.P) {
				if (a.CheckXY(v.X, v.Y)) return true;
			}
			return false;	
		}
				
		public override bool CollisionTest(Shape2D s, out Vector2D v) {
			v = null;
			return false;
	  	}		
						
		public override void Move(Vector2D v) {
			
		}
		
		public override void Offset(Vector2D v) {
			foreach (Vector2D vec in FVec) {
				vec.X += v.X;
				vec.Y += v.Y;
			}
		}
		
		public Polygon2D GetOffset(float x, float y) {
			return new Polygon2D(
			                     new Vector2D(FVec[0].X + x, FVec[0].Y + y),
			                     new Vector2D(FVec[1].X + x, FVec[1].Y + y),
			                     new Vector2D(FVec[2].X + x, FVec[2].Y + y));
		}
		
		
		public static Polygon2D operator* (Polygon2D a, Matrix2D m) {
			Polygon2D p = new Polygon2D();
			for (int i=0; i<3; i++) {
				p.FVec[i] = a.FVec[i] * m;
			}
			return p;
		}
	}
}
