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

namespace Hawkeye.VisionBuilder.Workflow.Operations.Filters;

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

    public int C1Min { get; set; }
    public int C1Max { get; set; }
    public int C2Min { get; set; }
    public int C2Max { get; set; }
    public int C3Min { get; set; }
    public int C3Max { get; set; }

    protected override void InterpretInternal(Context context)
    {
        if (!CheckImageExists(context)) return;
        var mat = context.ActiveImage.ImageData;
        var res = mat.InRange(new Scalar(C1Min, C2Min, C3Min), new Scalar(C1Max, C2Max, C3Max));
        context.ActiveImage = new HawkeyeImage() { ImageData = res };
        Status = "";
        Result = true;
    }

    public override void Save(BinaryWriter bw)
    {
        base.Save(bw);
        bw.Write(C1Min);
        bw.Write(C1Max);
        bw.Write(C2Min);
        bw.Write(C2Max);
        bw.Write(C3Min);
        bw.Write(C3Max);
    }

    public override void Load(BinaryReader br)
    {
        base.Load(br);
        C1Min = br.ReadInt32();
        C1Max = br.ReadInt32();
        C2Min = br.ReadInt32();
        C2Max = br.ReadInt32();
        C3Min = br.ReadInt32();
        C3Max = br.ReadInt32();
    }

    public override void Save(Dictionary<string, object> dict)
    {
        base.Save(dict);
        dict[nameof(C1Min)] = C1Min;
        dict[nameof(C1Max)] = C1Max;
        dict[nameof(C2Min)] = C2Min;
        dict[nameof(C2Max)] = C2Max;
        dict[nameof(C3Min)] = C3Min;
        dict[nameof(C3Max)] = C3Max;
    }

    public override void Load(Dictionary<string, object> dict)
    {
        base.Load(dict);
        if (dict.ContainsKey(nameof(C1Min)))
            C1Min = Convert.ToInt32(dict[nameof(C1Min)]);
        if (dict.ContainsKey(nameof(C1Max)))
            C1Max = Convert.ToInt32(dict[nameof(C1Max)]);
        if (dict.ContainsKey(nameof(C2Min)))
            C2Min = Convert.ToInt32(dict[nameof(C2Min)]);
        if (dict.ContainsKey(nameof(C2Max)))
            C2Max = Convert.ToInt32(dict[nameof(C2Max)]);
        if (dict.ContainsKey(nameof(C3Min)))
            C3Min = Convert.ToInt32(dict[nameof(C3Min)]);
        if (dict.ContainsKey(nameof(C3Max)))
            C3Max = Convert.ToInt32(dict[nameof(C3Max)]);
    }


}