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

namespace Hawkeye.VisionBuilder.Workflow.Operations;

[Category("Filters")]
public class NoiseFilterOperation:BaseOperation
{
    public int NoiseSize { get; set; }

    protected override void InterpretInternal(Context context)
    {
        if (!CheckImageExists(context)) return;
        if(!CheckGrayscale(context))return;
        if (NoiseSize < 1)
        {
            Status = $"{nameof(NoiseSize)} should be more than 0";
            Result = false;
            return;
        }
        context.ActiveImage = new HawkeyeImage()
        {
            ImageData = context.ActiveImage.ImageData.MorphologyEx(MorphTypes.Open, Cv2.GetStructuringElement(MorphShapes.Rect, new OpenCvSharp.Size(NoiseSize, NoiseSize)))
        };
        Status = $"Remove noise with size less than {NoiseSize}";
        Result = true;
    }

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

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

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

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