using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Drawing;

using bbiwarg.Recognition.HandRecognition;

using Emgu.CV;
using Emgu.CV.Structure;

namespace bbiwarg.Utility
{
    class Quadrangle
    {
        public Vector2D[] Vertices { get { return new Vector2D[4] { BottomLeft, TopLeft, TopRight, BottomRight }; } }
        public Vector2D BottomLeft { get; private set; }
        public Vector2D TopLeft { get; private set; }
        public Vector2D TopRight { get; private set; }
        public Vector2D BottomRight { get; private set; }
        public float Area {get; private set;}
        public Image<Gray, Byte> Mask { get; private set; }

        public Quadrangle(Vector2D bottomLeft, Vector2D topLeft, Vector2D topRight, Vector2D bottomRight, int width, int height)
        {
            BottomLeft = bottomLeft;
            TopLeft = topLeft;
            TopRight = topRight;
            BottomRight = bottomRight;

            Contour<PointF> contourPoints = new Contour<PointF>(new MemStorage());
            contourPoints.Push(BottomLeft);
            contourPoints.Push(TopLeft);
            contourPoints.Push(TopRight);
            contourPoints.Push(BottomRight);
            Area = (float) contourPoints.Area;

            Mask = new Image<Gray, byte>(width, height);

            Point[] polyPoints = new Point[4];
            polyPoints[0] = BottomLeft;
            polyPoints[1] = TopLeft;
            polyPoints[2] = TopRight;
            polyPoints[3] = BottomRight;
            Mask.FillConvexPoly(polyPoints, new Gray(255));
        }


        public Vector2D getRelativePosition(Vector2D p, Hand.HandSide side)
        {
            Vector2D a, b, c, d;

            if (side == Hand.HandSide.Left)
            {
                a = BottomLeft;
                b = TopLeft;
                c = TopRight;
                d = BottomRight;
            }
            else
            {
                a = BottomRight;
                b = TopRight;
                c = TopLeft;
                d = BottomLeft;
            }

            float C = (a.Y - p.Y) * (d.X - p.X) - (a.X - p.X) * (d.Y - p.Y);
            float B = (a.Y - p.Y) * (c.X - d.X) + (b.Y - a.Y) * (d.X - p.X) - (a.X - p.X) * (c.Y - d.Y) - (b.X - a.X) * (d.Y - p.Y);
            float A = (b.Y - a.Y) * (c.X - d.X) - (b.X - a.X) * (c.Y - d.Y);

            float D = B * B - 4 * A * C;

            float u = (-B - (float)Math.Sqrt(D)) / (2 * A);

            float p1x = a.X + (b.X - a.X) * u;
            float p2x = d.X + (c.X - d.X) * u;
            float px = p.X;

            float v = (px - p1x) / (p2x - p1x);

            return new Vector2D(v, u);
        }
    }
}
