using System.Diagnostics;
using OpenCvSharp;

namespace Hawkeye.VisionBuilder.Workflow.ColorStudioClasses.Filters;

public class MorphologyFilterItem:IFilter
{
    public enum EMorphologyType
    {
        Erode,
        Dilate,
        Close,
        Open
    }

    public int Size { get; set; } = 1;
    public EMorphologyType MorphologyType { get; set; }=EMorphologyType.Erode;
    public void Load(BinaryReader reader)
    {
        Size = reader.ReadInt32();
        MorphologyType = (EMorphologyType)reader.ReadInt32();
    }

    public bool IsSelected { get; set; }

    public IFilterParent Parent { get; set; }

    public MorphologyFilterItem()
    {
    }

    public MorphologyFilterItem(CategoryItem parent)
    {
        Parent = parent;
    }

    public void Transform(ref Mat image, ref Mat res)
    {
        if(Size==0)
            return;

        var sw=Stopwatch.StartNew();

        var kernel = Cv2.GetStructuringElement(MorphShapes.Ellipse,new Size((int)(Size), (int)(Size)));
        
        switch (MorphologyType)
        {
            case EMorphologyType.Dilate:
                //Cv2.Dilate(res, res,kernel);
                Cv2.MorphologyEx(res, res, MorphTypes.Dilate, kernel);
                break;
            case EMorphologyType.Erode:
                Cv2.Erode(res, res,kernel);
                break;
            case EMorphologyType.Close:
                Cv2.MorphologyEx(res, res, MorphTypes.Close, kernel);
                break;
            case EMorphologyType.Open:
                Cv2.MorphologyEx(res, res, MorphTypes.Open, kernel);
                break;
        }

        sw.Stop();
        
        
    }

    public void Save(BinaryWriter writer)
    {
        writer.Write(Size);
        writer.Write((int)MorphologyType);
    }

    public override string ToString()
    {
        return $"{MorphologyType} {Size}";
    }
}