using System;
using OpenCvSharp;

namespace OpenCVStudio_v0
{
    public sealed class SepFilter2DExecutor : IImageBlockExecutor
    {
        public string BlockType => "SepFilter2D";

        public Mat Execute(Mat input, ProjectBlock block, ProjectManager projectManager)
        {
            if (input == null)
                throw new ArgumentNullException(nameof(input));
            if (input.Empty())
            {
                throw new InvalidOperationException("SepFilter2D: изображение пустое.");
            }
            SepFilterKernel kernelType = projectManager.GetBlockParameter(block.Id, "Kernel", SepFilterKernel.Identity);
            using Mat kernelX = CreateKernel(kernelType);
            using Mat kernelY = CreateKernel(kernelType);
            Mat result = new Mat();
            Cv2.SepFilter2D(input, result, -1, kernelX, kernelY);
            return result;
        }

        private static Mat CreateKernel(SepFilterKernel type)
        {
            Mat kernel = new Mat(3, 1, MatType.CV_32FC1);
            float[] values = type switch
            {
                SepFilterKernel.Blur => new float[] { 1f / 3, 1f / 3, 1f / 3 },
                SepFilterKernel.Gaussian => new float[] { 0.25f, 0.5f, 0.25f },
                SepFilterKernel.Edge => new float[] { -1, 0, 1 },
                _ => new float[] { 0, 1, 0 }
            };
            for (int i = 0; i < 3; i++)
            {
                kernel.Set<float>(i, 0, values[i]);
            }
            return kernel;
        }
    }
}