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

namespace Hawkeye.VisionBuilder.Workflow.Operations.Morphology;

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

    public int Opening { get; set; } = 1;

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

        var element = Cv2.GetStructuringElement(MorphShapes.Rect, new Size(Opening, Opening));
        context.ActiveImage = new HawkeyeImage()
        {
            ImageData = context.ActiveImage!.ImageData.MorphologyEx(MorphTypes.Open, element)
        };

        Status = $"Opening {Opening}";
        Result = true;
    }

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

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

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

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