using System;
using System.IO;
using OpenCvSharp;

namespace OpenCVStudio_v0
{
    public sealed class ImageSaveExecutor : IImageBlockExecutor
    {
        public string BlockType =>
            "ImageSave";



        public Mat Execute(
            Mat input,
            ProjectBlock block,
            ProjectManager projectManager)
        {
            ArgumentNullException.ThrowIfNull(input);
            ArgumentNullException.ThrowIfNull(block);
            ArgumentNullException.ThrowIfNull(projectManager);


            if (input.Empty())
            {
                throw new InvalidOperationException(
                    "ImageSave: входное изображение пустое.");
            }



            string filePath =
                projectManager.GetBlockParameter(
                    block.Id,
                    "FilePath",
                    "result.png");



            ImageSaveFormat format =
                projectManager.GetBlockParameter(
                    block.Id,
                    "Format",
                    ImageSaveFormat.PNG);



            int quality =
                projectManager.GetBlockParameter(
                    block.Id,
                    "JpegQuality",
                    95);



            string? directory =
                Path.GetDirectoryName(filePath);



            if (!string.IsNullOrWhiteSpace(directory))
            {
                Directory.CreateDirectory(directory);
            }



            try
            {
                switch (format)
                {
                    case ImageSaveFormat.JPEG:

                        Cv2.ImWrite(
                            filePath,
                            input,
                            new ImageEncodingParam(
                                ImwriteFlags.JpegQuality,
                                quality));

                        break;



                    case ImageSaveFormat.PNG:

                        Cv2.ImWrite(
                            filePath,
                            input);

                        break;



                    case ImageSaveFormat.BMP:

                        Cv2.ImWrite(
                            filePath,
                            input);

                        break;



                    case ImageSaveFormat.TIFF:

                        Cv2.ImWrite(
                            filePath,
                            input);

                        break;


                    default:

                        Cv2.ImWrite(
                            filePath,
                            input);

                        break;
                }


                return input;
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException(
                    $"Ошибка сохранения изображения: {filePath}",
                    ex);
            }
        }
    }
}