using System;
using OpenCvSharp;

namespace OpenCVStudio_v0
{
    internal sealed class ConvexHullExecutor : IPipelineBlockExecutor
    {
        public string BlockType => "ConvexHull";

        public void Execute(PipelineContext context, ProjectBlock block, ProjectManager projectManager)
        {
            ArgumentNullException.ThrowIfNull(context);
            ArgumentNullException.ThrowIfNull(block);
            if (context.Contours == null)
            {
                throw new InvalidOperationException($"Блок «{block.Name}»: нет контуров. Добавьте FindContours перед ним.");
            }
            OpenCvSharp.Point[][] contours = context.Contours.Contours;
            OpenCvSharp.Point[][] hulls = new OpenCvSharp.Point[contours.Length][];
            for (int i = 0; i < contours.Length; i++)
            {
                OpenCvSharp.Point[] contour = contours[i];
                if (contour == null || contour.Length == 0)
                {
                    hulls[i] = Array.Empty<OpenCvSharp.Point>();
                    continue;
                }
                hulls[i] = Cv2.ConvexHull(contour);
            }
            context.ConvexHulls = new ConvexHullData(hulls);
            context.ResultText = $"Выпуклых оболочек: {hulls.Length}";
        }
    }
}