using System.Collections.Generic;
using System.Linq;
using CrossCutting;
using MoreLinq;
using OpenCvSharp;
using OpenCvSharp.Blob;
using Point = OpenCvSharp.Point;

namespace InterpreterLibrary.Interpreters
{
    internal class InkElement : TextElement
    {
        private readonly List<CvBlob> _blobs = new List<CvBlob>();
        public IReadOnlyCollection<CvBlob> Blobs => _blobs.AsReadOnly();
        public CharacterClassificationResult Interpretation => Interpretations?.MaxBy(ip => ip.Confidence).FirstOrDefault();
        public IEnumerable<CharacterClassificationResult> Interpretations { get; set; }

        public Rect Bounds
        {
            get
            {
                if (_blobs.Count == 0)
                {
                    return Rect.Empty;
                }

                if (_blobs.Count == 1)
                {
                    return _blobs.First().Rect;
                }
                var left = (from blob in _blobs select blob.Rect.X).Min();
                var top = (from blob in _blobs select blob.Rect.Y).Min();
                var right = (from blob in _blobs select blob.Rect.X + blob.Rect.Width - 1).Max();
                var bottom = (from blob in _blobs select blob.Rect.Y + blob.Rect.Height - 1).Max();
                return Rect.FromLTRB(left, top, right, bottom);
            }
        }

        public void AddBlob(CvBlob blob)
        {
            _blobs.Add(blob);
        }

        public IEnumerable<Point> GetConvexHull()
        {
            return Cv2.ConvexHull(_blobs.SelectMany(blob => blob.Contour.ConvertToPolygon().AsReadOnly()).ToList());
        }


    }

}

