using Hawkeye.VisionBuilder.Workflow.Datatypes.Elements.Line;
using Hawkeye.VisionBuilder.Workflow.Operations.Attributes;
using OpenCvSharp.Extensions;
using Point = OpenCvSharp.Point;

namespace Hawkeye.VisionBuilder.Workflow.Operations.Basic;

[Category("Basic")]
public class PorabollisticHoughOperation:BaseOperation
{
    public double DistanceResolution { get; set; } = 1;
    public double AngleResolution { get; set; } = Math.PI / 180.0;
    public int Threshold { get; set; } = 50;
    public int MinLineLength { get; set; } = 50;
    public int MaxLineGap { get; set; } = 10;

    protected override void InterpretInternal(Context context)
    {
        if (!CheckImageExists(context)) return;
        
        var segments = context.ActiveImage.ImageData.HoughLinesP(DistanceResolution, AngleResolution, Threshold, MinLineLength, MaxLineGap);

        foreach (var segment in segments)
        {
            context.GraphicsElements.Add(new LineElement()
            {
                Start = new Vector2(segment.P1.X, segment.P1.Y),
                End = new Vector2(segment.P2.X, segment.P2.Y)
            });
        }

        Result = true;
    }

    public override void Save(BinaryWriter bw)
    {
        base.Save(bw);
        bw.Write(DistanceResolution);
        bw.Write(AngleResolution);
        bw.Write(Threshold);
        bw.Write(MinLineLength);
        bw.Write(MaxLineGap);
    }

    public override void Load(BinaryReader br)
    {
        base.Load(br);
        DistanceResolution = br.ReadDouble();
        AngleResolution = br.ReadDouble();
        Threshold = br.ReadInt32();
        MinLineLength = br.ReadInt32();
        MaxLineGap = br.ReadInt32();
    }

    public override void Save(Dictionary<string, object> dict)
    {
        base.Save(dict);
        dict[nameof(DistanceResolution)] = DistanceResolution;
        dict[nameof(AngleResolution)] = AngleResolution;
        dict[nameof(Threshold)] = Threshold;
        dict[nameof(MinLineLength)] = MinLineLength;
        dict[nameof(MaxLineGap)] = MaxLineGap;
    }

    public override void Load(Dictionary<string, object> dict)
    {
        base.Load(dict);
        if (dict.ContainsKey(nameof(DistanceResolution)))
            DistanceResolution = Convert.ToDouble(dict[nameof(DistanceResolution)]);
        if (dict.ContainsKey(nameof(AngleResolution)))
            AngleResolution = Convert.ToDouble(dict[nameof(AngleResolution)]);
        if (dict.ContainsKey(nameof(Threshold)))
            Threshold = Convert.ToInt32(dict[nameof(Threshold)]);
        if (dict.ContainsKey(nameof(MinLineLength)))
            MinLineLength = Convert.ToInt32(dict[nameof(MinLineLength)]);
        if (dict.ContainsKey(nameof(MaxLineGap)))
            MaxLineGap = Convert.ToInt32(dict[nameof(MaxLineGap)]);
    }
}