using IWS5.Importer.Abstractions.FileSystem;
using Syncfusion.Pdf;
using Syncfusion.Pdf.Graphics;
using Syncfusion.Drawing;
using IWS5.Importer.Abstractions.Enums;

namespace IWS5.Importer.Worker.Conversion;

public class TiffFileConverter : IFileConverter
{
    private static readonly HashSet<string> Extensions = new(StringComparer.OrdinalIgnoreCase)
    {
        SupportedExtension.Bmp.ToString().ToLowerInvariant(),
        SupportedExtension.Gif.ToString().ToLowerInvariant(),
        SupportedExtension.Tif.ToString().ToLowerInvariant(),
        SupportedExtension.Tiff.ToString().ToLowerInvariant()
    };

    public bool CanConvert(string extension) => Extensions.Contains(extension);

    public async Task ConvertAsync(string inputPath, string outputPath, CancellationToken cancellationToken)
    {
        using FileStream tiffStream = new FileStream(inputPath, FileMode.Open, FileAccess.Read);
        using PdfDocument document = new PdfDocument();
        PdfTiffImage tiffImage = new PdfTiffImage(tiffStream);

        int frameCount = tiffImage.FrameCount;

        for (int i = 0; i < frameCount; i++)
        {
            PdfPage page = document.Pages.Add();
            SizeF pageSize = page.GetClientSize();
            tiffImage.ActiveFrame = i;

            page.Graphics.DrawImage(tiffImage, 0, 0, pageSize.Width, pageSize.Height);
        }

        using FileStream pdfStream = new FileStream(outputPath, FileMode.Create, FileAccess.Write);
        document.Save(pdfStream);
        document.Close(true);

        await Task.CompletedTask;
    }
}