using System;
using OpenCvSharp;

namespace NistUtilities.OpenCvSharp
{
    public class EmnistAdapter : NistAdapter
    {
        public EmnistAdapter(Mat sourceBitmap) : base(sourceBitmap)
        {
        }

        public override Mat To28X28()
        {
            const int padding = 2;
            const double sigma = 1;
            var roiBitmap = FindRegionOfInterest();
            var paddedBitmap = PadAndSquareBitmap(roiBitmap, padding);
            var blurredBitmap = new Mat();
            Cv2.GaussianBlur(paddedBitmap, blurredBitmap, Size.Zero, sigma);
            var ret = new Mat();
            Cv2.Resize(blurredBitmap, ret, new Size(28, 28));
            return ret;
        }

        private static Mat PadAndSquareBitmap(Mat bitmap, int padding)
        {
            var size = Math.Max(bitmap.Width, bitmap.Height) + 2 * padding;
            var ret = new Mat(size, size, bitmap.Type(), Scalar.White);

            var origin = new Point(
                ret.Width / 2 - bitmap.Width / 2,
                ret.Height / 2 - bitmap.Height / 2);
            var destRect = new Rect(origin, bitmap.Size());
            var srcRect = new Rect(0, 0, bitmap.Width, bitmap.Height);
            bitmap.SubMat(srcRect).CopyTo(ret.SubMat(destRect));
            return ret;
        }
    }
}

