using Syncfusion.Pdf.Parsing;
using Syncfusion.PdfToImageConverter;

namespace IWS5.Server.Utils.Converter.TiffConverter;

public static class PdfToTiffConverter
{
    /// <summary>
    /// Converts PDF bytes to TIFF bytes with multi-page support
    /// </summary>
    /// <param name="pdfBytes">The PDF file as byte array</param>
    /// <param name="dpi">DPI for the conversion (default: 200)</param>
    /// <returns>TIFF file as byte array</returns>
    public static async Task<byte[]> ConvertAsync(byte[] pdfBytes, int dpi = 200)
    {
        if (pdfBytes == null || pdfBytes.Length == 0)
            throw new ArgumentException("PDF bytes cannot be null or empty.", nameof(pdfBytes));

        if (dpi <= 0)
            throw new ArgumentException("DPI must be greater than 0.", nameof(dpi));

        try
        {
            using var pdfStream = new MemoryStream(pdfBytes);
            using var pdfDocument = new PdfLoadedDocument(pdfStream);
            
            using var converterStream = new MemoryStream(pdfBytes);
            var pdfToImageConverter = new PdfToImageConverter(converterStream);
            
            // Convert each page individually
            var imageStreams = new List<Stream>();
            var bitmaps = new List<System.Drawing.Bitmap>();
            
            try
            {
                for (int pageIndex = 0; pageIndex < pdfDocument.Pages.Count; pageIndex++)
                {
                    // Convert single page
                    var imageStream = pdfToImageConverter.Convert(pageIndex, true, false);
                    
                    if (imageStream != null)
                    {
                        imageStreams.Add(imageStream);
                        var bitmap = new System.Drawing.Bitmap(imageStream);
                        bitmap.SetResolution(dpi, dpi);
                        bitmaps.Add(bitmap);
                    }
                }

                if (bitmaps.Count == 0)
                    throw new InvalidOperationException("Failed to convert any PDF pages to images.");

                return await TiffUtilities.CreateMultiPageTiffAsync(bitmaps.ToArray(), dpi);
            }
            finally
            {
                foreach (var bitmap in bitmaps)
                    bitmap?.Dispose();
                    
                foreach (var stream in imageStreams)
                    stream?.Dispose();
            }
        }
        catch (Exception ex)
        {
            throw new InvalidOperationException($"Error converting PDF to TIFF: {ex.Message}", ex);
        }
    }
}