using System.IO;
using BallotTemplates;
using InterpreterLibrary.Processing;
using OpenCvSharp;

namespace InterpreterLibrary.Interpreters
{
    public class AdjustmentMarkChecker
    {
        private readonly Mat _mask;
        public AdjustmentMarkType Type { get; }

        public AdjustmentMarkChecker(AdjustmentMarkType type)
        {
            Type = type;
            var assembly = typeof(AdjustmentMarkChecker).Assembly;
            Stream stream;

            switch (type)
            {
                case AdjustmentMarkType.RightTack:
                    stream = assembly.
                        GetManifestResourceStream("InterpreterLibrary.res.RightTack-mask.bmp");
                    break;
                case AdjustmentMarkType.UpsideDownL:
                    stream = assembly.
                        GetManifestResourceStream("InterpreterLibrary.res.UpsideDownL-mask.bmp");
                    break;
                case AdjustmentMarkType.MirroredL:
                    stream = assembly.
                        GetManifestResourceStream("InterpreterLibrary.res.MirroredL-mask.bmp");
                    break;
                case AdjustmentMarkType.DoubleT:
                    stream = assembly.
                        GetManifestResourceStream("InterpreterLibrary.res.DoubleT-mask.bmp");
                    break;
                case AdjustmentMarkType.T:
                    stream = assembly.
                        GetManifestResourceStream("InterpreterLibrary.res.T-mask.bmp");
                    break;
                default:
                    stream = null;
                    break;
            }

            if (stream == null)
            {
                _mask = null;
            }
            else
            {
                using (var ms = new MemoryStream())
                {
                    stream.CopyTo(ms);
                    _mask = Mat.FromImageData(ms.ToArray(), ImreadModes.GrayScale);
                }
            }
        }

        public bool IsMatch(Mat image)
        {
            const int minFillPercentage = 85;
            var resizedMask = _mask.Resize(new Size(image.Width, image.Height), 0d, 0d, InterpolationFlags.Nearest);
            var result = new Mat();
            Cv2.Absdiff(resizedMask, image, result);
            var fill = result.GetFillPercentage();
            return fill >= minFillPercentage;
        }
    }
}

