using IWS5.Importer.Abstractions.FileSystem;
using Syncfusion.XlsIO;
using Syncfusion.XlsIORenderer;
using Syncfusion.Pdf;
using IWS5.Importer.Abstractions.Enums;

namespace IWS5.Importer.Worker.Conversion;

public class ExcelFileConverter : IFileConverter
{
    private static readonly HashSet<string> Extensions = new(StringComparer.OrdinalIgnoreCase)
    {
        SupportedExtension.Xls.ToString().ToLowerInvariant(),
        SupportedExtension.Xlsx.ToString().ToLowerInvariant()
    };

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

    public async Task ConvertAsync(string inputPath, string outputPath, CancellationToken cancellationToken)
    {
        using ExcelEngine excelEngine = new ExcelEngine();
        IApplication application = excelEngine.Excel;
        application.DefaultVersion = ExcelVersion.Xlsx;

        using FileStream excelStream = new FileStream(inputPath, FileMode.Open, FileAccess.Read);
        IWorkbook workbook = application.Workbooks.Open(excelStream);

        XlsIORenderer renderer = new XlsIORenderer();
        PdfDocument pdfDocument = renderer.ConvertToPDF(workbook);

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

        await Task.CompletedTask;
    }
}
