using System;
using OpenCvSharp;

namespace NistUtilities.OpenCvSharp
{
    public class MnistAdapter : NistAdapter
    {

        public MnistAdapter(Mat bitmap) : base(bitmap)
        {

        }
        public override Mat To28X28()
        {
            var roiBitmap = FindRegionOfInterest();

            var scaleFactor = roiBitmap.Width > roiBitmap.Height
                ? 20f / roiBitmap.Width
                : 20f / roiBitmap.Height;

            var newSize = new Size(
                (int)(roiBitmap.Width * scaleFactor),
                (int)(roiBitmap.Height * scaleFactor));
            var resized = new Mat();
            Cv2.Resize(roiBitmap, resized, newSize, 0, 0, InterpolationFlags.Area);

            var centerOfMass = FindCenterOfMass(resized);
            if (float.IsNaN(centerOfMass.X) || float.IsNaN(centerOfMass.Y))
            {
                centerOfMass = new Point2f(newSize.Width / 2f, newSize.Height / 2f);
            }
            var originX = (int)(28f / 2 - centerOfMass.X);
            var originY = (int)(28f / 2 - centerOfMass.Y);
            var targetRect = new Rect(originX, originY, resized.Width, resized.Height);
            var ret = new Mat(28, 28, Bitmap.Type(), Scalar.White);
            resized.CopyTo(ret.SubMat(targetRect));
            return ret;
        }
        private static (int ShiftX, int ShiftY) GetBestShift(Mat img)
        {
            var centerOfMass = FindCenterOfMass(img);
            if (float.IsNaN(centerOfMass.X) || float.IsNaN(centerOfMass.Y))
            {
                return (0, 0);
            }
            var shiftx = (int)Math.Round(img.Width / 2.0 - centerOfMass.X);
            var shifty = (int)Math.Round(img.Height / 2.0 - centerOfMass.Y);
            return (shiftx, shifty);
        }

        private static Mat Shift(Mat img, int sx, int sy)
        {
            var imgOut = new Mat(img.Size(), img.Type());

            var srcRoi = img.BoundingRect();
            var dstRoi = new Rect(new Point(srcRoi.X + sx, srcRoi.Y + sy), img.Size());
            img.SubMat(srcRoi).CopyTo(imgOut.SubMat(dstRoi));
            return imgOut;
        }


    }
}

