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

namespace Hawkeye.VisionBuilder.Workflow.Operations.Basic;

[Category("Basic")]
public class DetectionPaddingOperation:BaseOperation
{
    public int HorizontalPadding { get; set; }
    public int VerticalPadding { get; set; }


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

        // fill edges with black on top and bottom without changing the image size
        var image = context.ActiveImage;
        var newImage = new Mat(image.ImageData.Rows, image.ImageData.Cols, MatType.CV_8UC1, Scalar.Black);

        
        
        var mask = new Mat(image.ImageData.Rows, image.ImageData.Cols, MatType.CV_8UC1, Scalar.Black);
        var maskRoi = mask[VerticalPadding, image.ImageData.Rows - VerticalPadding, HorizontalPadding, image.ImageData.Cols - HorizontalPadding];
        //fill the mask with white
        maskRoi.SetTo(Scalar.White);

        image.ImageData.CopyTo(newImage, mask);
        
        mask.Dispose();
        maskRoi.Dispose();
        context.ActiveImage = new HawkeyeImage()
        {
            ImageData = newImage
        };


    }

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

    public override void Load(BinaryReader br)
    {
        base.Load(br);
        HorizontalPadding = br.ReadInt32();
        VerticalPadding = br.ReadInt32();
    }

    public override void Save(Dictionary<string, object> dict)
    {
        base.Save(dict);
        dict[nameof(HorizontalPadding)] = HorizontalPadding;
        dict[nameof(VerticalPadding)] = VerticalPadding;
    }

    public override void Load(Dictionary<string, object> dict)
    {
        base.Load(dict);
        if (dict.ContainsKey(nameof(HorizontalPadding)))
            HorizontalPadding = Convert.ToInt32(dict[nameof(HorizontalPadding)]);
        if (dict.ContainsKey(nameof(VerticalPadding)))
            VerticalPadding = Convert.ToInt32(dict[nameof(VerticalPadding)]);
    }
}