
using OpenCvSharp;

namespace Hawkeye.VisionBuilder.Workflow.Datatypes.Elements.ArrayHorizontal;

public class ArrayHorizontalElement:IGraphicsElement
{
    public bool Editable { get; set; }

    public Dictionary<int,bool> IsGood=new Dictionary<int, bool>();

    public Vector2 Location { get; set; }
    public Vector2 Offset { get; set; }

    
    public Vector2 BlockSize { get; set; }
    public int Margin { get; set; } = 5;
    public int BlockCount { get; set; } = 5;

    public void Draw(ICanvas canvas)
    {
        GenerateLocations().Select((l, i) => (l, i)).ToList().ForEach(((Vector2 l, int i) x) => canvas.DrawRectangle(x.l, BlockSize, IsGood.GetValueOrDefault(x.i,true)));
        canvas.DrawNode(Offset + Location);
        
    }

    public IEnumerable<Vector2> GenerateLocations()
    {
        for (int i = 0; i < BlockCount; i++)
            yield return Offset + Location + (new Vector2(1, 0) * i * (BlockSize.X + Margin));
    }

    public void FillMat(Mat mat)
    {
        
    }


    public INode? GetNode(Vector2 position, float thDistance)
    {
        if ((Location + Offset - position).Length() < thDistance)
        {
            return new ArrayHorizontalAnchorNode(this);
        }


        return null;
    }

    public void SetPivot(Vector2 pivot)
    {
        Location += Offset;
        Offset = pivot;
        Location -= Offset;
    }

    public void MovePivot(Vector2 pivot)
    {
        Offset = pivot;
    }




    public void Save(BinaryWriter bw)
    {
        bw.Write(Editable);
        bw.Write(Location.X);
        bw.Write(Location.Y);
        bw.Write(Offset.X);
        bw.Write(Offset.Y);
        bw.Write(BlockSize.X);
        bw.Write(BlockSize.Y);
        bw.Write(BlockCount);
        
    }

    public void Load(BinaryReader br)
    {
        Editable = br.ReadBoolean();
        Location = new Vector2(br.ReadSingle(), br.ReadSingle());
        Offset = new Vector2(br.ReadSingle(), br.ReadSingle());
        BlockSize = new Vector2(br.ReadSingle(), br.ReadSingle());
        BlockCount = br.ReadInt32();
    }
}