using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using bbiwarg.Recognition.FingerRecognition;
using Emgu.CV.Structure;

namespace bbiwarg.Utility
{
    public class ConvexityDefect
    {
        public Vector2D OuterShort { get; private set; }
        public Vector2D OuterLong { get; private set; }
        public Vector2D Inner { get; private set; }
        public Vector2D VectorShort { get; private set; }
        public Vector2D VectorLong { get; private set; }
        public LineSegment2D OuterLineSegment { get; private set; }
        public float Depth { get; private set; }

        public ConvexityDefect(MCvConvexityDefect mcvCOnvexityDefect) {
            Inner = new Vector2D(mcvCOnvexityDefect.DepthPoint);
            Vector2D p1 = new Vector2D(mcvCOnvexityDefect.StartPoint);
            Vector2D p2 = new Vector2D(mcvCOnvexityDefect.EndPoint);

            if ((p1 - Inner).Length > (p2 - Inner).Length)
            {
                OuterLong = p1;
                OuterShort = p2;
            }
            else {
                OuterLong = p2;
                OuterShort = p1;
            }

            VectorLong = OuterLong - Inner;
            VectorShort = OuterShort - Inner;
            OuterLineSegment = new LineSegment2D(OuterLong, OuterShort);
            Depth = OuterLineSegment.getDistanceTo(Inner);
        }

        public bool isPossibleThumbDefect(Finger thumb) {
            float tipDistance = thumb.TipPoint.getDistanceTo(OuterShort);
            float handDistance = thumb.HandPoint.getDistanceTo(Inner);
            float thumbShortLengthRatio = thumb.LineSegment.Length / VectorShort.Length;
            float shortLongLengthRatio = VectorShort.Length / VectorLong.Length;

            return (tipDistance <= Parameters.HandThumbDefectMaxDistanceToThumb &&
                    handDistance <= Parameters.HandThumbDefectMaxDistanceToThumb &&
                    thumbShortLengthRatio <= Parameters.HandThumbDefectMaxThumbShortLengthRatio && thumbShortLengthRatio >= Parameters.HandThumbDefectMinThumbShortLengthRatio &&
                    shortLongLengthRatio <= Parameters.HandThumbDefectMaxShortLongLengthRatio && shortLongLengthRatio >= Parameters.HandThumbDefectMinShortLongLengthRatio);
        }

        public bool isCausedByFinger(Finger finger) {
            return (OuterLineSegment.intersectsWith(finger.LineSegment));
        }
    }
}
