using System.Collections;
using Hawkeye.VisionBuilder.Workflow.Datatypes;
using Hawkeye.VisionBuilder.Workflow.Operations.Attributes;
using OpenCvSharp;

namespace Hawkeye.VisionBuilder.Workflow.Operations.Morphology;

[Category("Morphology")]
public class TakeBiggestOperation : BaseOperation
{
    public TakeBiggestOperation()
    {
        CanHaveProcessingError = false;
    }

    protected override void InterpretInternal(Context context)
    {
        if (!CheckImageExists(context)) return;
        if (!CheckGrayscale(context)) return;

        var image = context.ActiveImage!.ImageData;
        
        Cv2.FindContours(image, out var contours, out var hierarchy, RetrievalModes.External, ContourApproximationModes.ApproxSimple);

        if (contours.Length == 0)
        {
            SetError("No blobs found.");
            return;
        }

        var largestContour = contours.OrderByDescending(c => Cv2.ContourArea(c)).First();
        var mask = Mat.Zeros(image.Size(), MatType.CV_8UC1).ToMat();
        
        Cv2.DrawContours(mask, new[] {largestContour}, -1, Scalar.All(255), -1);

        context.ActiveImage = new HawkeyeImage()
        {
            ImageData = mask
        };

        Status = "Biggest blob extracted";
        Result = true;
    }

    public override void Save(BinaryWriter bw)
    {
        base.Save(bw);
    }

    public override void Load(BinaryReader br)
    {
        base.Load(br);
    }

    public override void Save(Dictionary<string, object> dict)
    {
        base.Save(dict);
    }

    public override void Load(Dictionary<string, object> dict)
    {
        base.Load(dict);
    }
}
