using System;
using System.Collections.Generic;
using System.Linq;
using CrossCutting;
using OpenCvSharp;

namespace InterpreterLibrary.Models.Transform
{
    internal static class HomographicTransformer
    {

        public static Mat TransformMat(Mat image, IReadOnlyList<Tuple<PointF, PointF>> pointPairs)
        {
            var maxX2 = pointPairs.Max(pair => pair.Item2.X);
            var maxY2 = pointPairs.Max(pair => pair.Item2.Y);
            Size newSize;
            if (maxX2 > 0 && maxY2 > 0)
            {
                var xScale = pointPairs.Max(pair => pair.Item1.X) / pointPairs.Max(pair => pair.Item2.X);
                var yScale = pointPairs.Max(pair => pair.Item1.Y) / pointPairs.Max(pair => pair.Item2.Y);
                newSize = new Size(image.Width * xScale, image.Height * yScale);
            }
            else
            {
                newSize = new Size(image.Width , image.Height );
            }

            var q = from pair in pointPairs select new Point2d(pair.Item1.X, pair.Item1.Y);
            var p = from pair in pointPairs select new Point2d(pair.Item2.X, pair.Item2.Y);
            var homo = Cv2.FindHomography(p, q);
            var transformedMat = new Mat();
            Cv2.WarpPerspective(image, transformedMat, homo, newSize, InterpolationFlags.Nearest, BorderTypes.Constant, Scalar.White);

            return transformedMat;
        }
    }
}

