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

namespace Hawkeye.VisionBuilder.Workflow.Operations.Basic;

[Category("Basic")]
public class SkeletonOperation:BaseOperation
{
    protected override void InterpretInternal(Context context)
    {
        if (!CheckImageExists(context)) return;
        if(!CheckGrayscale(context)) return;


        var skeleton = new Mat(context.ActiveImage.ImageData.Size(), MatType.CV_8UC1, Scalar.All(0));
        var temp = context.ActiveImage.ImageData.Clone();
        var element = Cv2.GetStructuringElement(MorphShapes.Cross, new OpenCvSharp.Size(3, 3));
        var image = context.ActiveImage.ImageData.Clone();

        do
        {
            var eroded = image.Erode(element);
            
            temp =eroded.Dilate(element);
            
            Cv2.Subtract(image,temp, temp);
            Cv2.BitwiseOr(skeleton, temp, skeleton);
            
            eroded.CopyTo(image);
        } while (Cv2.CountNonZero(image) != 0);

        context.ActiveImage = new HawkeyeImage()
        {
            ImageData = skeleton
        };

        Result = true;
    }   
}