using System.Text;
using OpenCvSharp;

namespace Hawkeye.VisionBuilder.Workflow.ColorStudioClasses.Filters;

public class BlobsFilterItem:IFilter
{
    public int MinArea { get; set; } = 0;
    public int MaxArea { get; set; } = 999999;
    public int MinRadius { get; set; } = 0;
    public int MaxRadius { get; set; } = 999999;

    public IFilterParent Parent { get; set; }
    public void Transform(ref Mat image, ref Mat res)
    {
        var contours = res
            .FindContoursAsArray(RetrievalModes.List, ContourApproximationModes.ApproxSimple);

        Mat result = new Mat(res.Rows, res.Cols, MatType.CV_8U, new Scalar(0));

        foreach (Point[] contour in contours)
        {
            var area = Cv2.ContourArea(contour);
            if (area < MinArea || area > MaxArea)
                continue;
            var radius = GetContourRadius(contour);
            if (radius < MinRadius || radius > MaxRadius)
                continue;

            Cv2.DrawContours(result, new[] { contour }, -1, new Scalar(255), -1);
        }

        res = result;
    }
    int GetContourRadius(Point[] contour)
    {
        Cv2.MinEnclosingCircle(contour, out var center, out var radius);
        return (int)radius;
    }
    public void Save(BinaryWriter writer)
    {
        writer.Write(MinArea);
        writer.Write(MaxArea);
        writer.Write(MinRadius);
        writer.Write(MaxRadius);
    }

    public void Load(BinaryReader reader)
    {
        MinArea = reader.ReadInt32();
        MaxArea = reader.ReadInt32();
        MinRadius = reader.ReadInt32();
        MaxRadius = reader.ReadInt32();
    }

    public bool IsSelected { get; set; }

    public override string ToString()
    {
        StringBuilder sb = new StringBuilder();
        sb.Append("Blobs: ");
        sb.Append($"Area:{MinArea}-{MaxArea}, ");
        sb.Append($"Radius:{MinRadius}-{MaxRadius}");
        return sb.ToString();
    }
}