using System.Drawing;
using IWS5.Server.Enums;

namespace IWS5.Server.Utils.Converter.TiffConverter;

internal class ImageFileToTiffConverter : IFileConverter
{
    private static readonly HashSet<string> Extensions = new(StringComparer.OrdinalIgnoreCase)
    {
        ConvertibleFileTypes.jpeg.ToString().ToLowerInvariant(),
        ConvertibleFileTypes.jpg.ToString().ToLowerInvariant(),
        ConvertibleFileTypes.png.ToString().ToLowerInvariant()
    };

    public bool CanConvert(string sourceFileExtension, string targetFileExtension) => Extensions.Contains(sourceFileExtension) && 
        string.Equals(targetFileExtension, nameof(ConvertibleFileTypes.tiff), StringComparison.OrdinalIgnoreCase);

    public async Task<byte[]> ConvertAsync(byte[] inputFile)
    {
        try
        {
            using var inputStream = new MemoryStream(inputFile);
            using var inputImage = new Bitmap(inputStream);
            
            // Create array with single image
            var bitmaps = new[] { inputImage };

            return await TiffUtilities.CreateMultiPageTiffAsync(bitmaps);
        }
        catch (Exception ex)
        {
            throw new InvalidOperationException($"Error converting image to TIFF: {ex.Message}", ex);
        }
    }
}