using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using bbiwarg.Utility;
using bbiwarg.Recognition.HandRecognition;
using bbiwarg.Recognition.Tracking;

namespace bbiwarg.Recognition.PalmRecognition
{
    public enum HandSide
    {
        Undefined = 0,
        Right = 1,
        Left = 2
    }

    public class Palm : TrackableObject
    {
        public Hand Hand { get; private set; }
        public ConvexityDefect ThumbDefect { get; private set; }
        public HandSide HandSide { get; private set; }
        public Vector2D WristUpper { get; private set; }
        public Vector2D FingersUpper { get; private set; }
        public Vector2D FingersLower { get; private set; }
        public Vector2D WristLower { get; private set; }
        public Quadrangle Quad { get; private set; }

        public Palm(Hand hand, ConvexityDefect thumbDefect, HandSide handSide, Vector2D wristUpper, Vector2D fingersUpper, Vector2D fingersLower, Vector2D wristLower)
        {
            Hand = hand;
            ThumbDefect = thumbDefect;
            HandSide = handSide;
            WristUpper = wristUpper;
            FingersUpper = fingersUpper;
            FingersLower = fingersLower;
            WristLower = wristLower;

            hand.Palm = this;

            createQuad();
        }

        public Vector2D getRelativePosition(Vector2D absolutePosition)
        {
            Vector2D relativePosition = Quad.getRelativePosition(absolutePosition);
            float x = Math.Max(0, Math.Min(1, relativePosition.X));
            float y = Math.Max(0, Math.Min(1, relativePosition.Y));

            return new Vector2D(x, y);
        }

        public bool isInside(Vector2D position)
        {
            return Quad.isInside(position, Parameters.PalmInsideTolerance);
        }

        private void createQuad()
        {
            if (HandSide == HandSide.Left)
                Quad = new Quadrangle(WristUpper, FingersUpper, FingersLower, WristLower);
            else
                Quad = new Quadrangle(FingersUpper, WristUpper, WristLower, FingersLower);
        }
    }
}
