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

namespace Hawkeye.VisionBuilder.Workflow.Operations.Basic;

[Category("Basic")]
public class GaussianBlurOperation : BaseOperation
{
    public ScriptValue KernelSize { get; set; } = new ScriptValue() { Script = "3" };


    protected override void InterpretInternal(Context context)
    {
        if (!CheckImageExists(context)) return;
        var kernelSize = GetScriptValue<int>(KernelSize);
        if (kernelSize < 1||IsEven(kernelSize))
        {
            Status = $"{nameof(KernelSize)} should be more than 0 and be odd number";
            Result = false;
            return;
        }

        context.ActiveImage = new HawkeyeImage()
        {
            ImageData = context.ActiveImage.ImageData.GaussianBlur(new OpenCvSharp.Size(kernelSize, kernelSize), 0, 0)
        };
        Status = $"Gaussian blur with kernel size {KernelSize}";
        Result = true;
    }

    private bool IsEven(int kernelSize)
    {
        return kernelSize % 2 == 0;
    }


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

    public override void Load(BinaryReader br)
    {
        base.Load(br);
        KernelSize.Script = br.ReadString();
        
    }

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

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