using OpenCvSharp;

namespace Hawkeye.VisionBuilder.Workflow.ColorStudioClasses.Filters;

public class IntersectionFilterItem : IFilter, IFilterParent
{
    public IFilterParent Parent { get; set; }

    public List<IFilter> Filters { get; set; } = new List<IFilter>();

    public void Transform(ref Mat image, ref Mat res)
    {
        using var tracker = new ResourcesTracker();
        var temp = tracker.NewMat(res.Size(), MatType.CV_8UC1, Scalar.Black);
        foreach (var filter in Filters)
        {
            filter.Transform(ref image, ref temp);
        }
        res = res & temp;
        temp.Dispose();
    }

    public void Save(BinaryWriter bw)
    {
        bw.Write(Filters.Count);
        foreach (var filter in Filters)
        {
            bw.Write(filter.GetType().FullName);
            filter.Save(bw);
        }
    }

    public void Load(BinaryReader reader)
    {
        int count = reader.ReadInt32();
        for (int i = 0; i < count; i++)
        {
            var type = reader.ReadString();
            var filter = (IFilter)Activator.CreateInstance(Type.GetType(type));
            filter.Load(reader);
            filter.Parent = this;
            Filters.Add(filter);
        }
    }

    public bool IsSelected { get; set; }

    public override string ToString()
    {
        return "Intersection";
    }
}