using IWS5.Importer.Abstractions.FileSystem;
using IWS5.Importer.Abstractions.Enums;
using Syncfusion.DocIO;
using Syncfusion.DocIO.DLS;
using Syncfusion.DocIORenderer;
using Syncfusion.Pdf;

namespace IWS5.Importer.Worker.Conversion;

public class WordFileConverter : IFileConverter
{
    private static readonly HashSet<string> Extensions = new(StringComparer.OrdinalIgnoreCase)
    {
        SupportedExtension.Doc.ToString().ToLowerInvariant(),
        SupportedExtension.Docx.ToString().ToLowerInvariant(),
        SupportedExtension.Docm.ToString().ToLowerInvariant(),
        SupportedExtension.Rtf.ToString().ToLowerInvariant(),
        SupportedExtension.Txt.ToString().ToLowerInvariant(),
        SupportedExtension.Md.ToString().ToLowerInvariant(),
        SupportedExtension.Html.ToString().ToLowerInvariant(),
    };

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

    public async Task ConvertAsync(string inputPath, string outputPath, CancellationToken cancellationToken)
    {
        using FileStream docStream = new FileStream(inputPath, FileMode.Open, FileAccess.Read);
        using WordDocument wordDocument = new WordDocument(docStream, FormatType.Automatic);
        using DocIORenderer renderer = new DocIORenderer();
        PdfDocument pdf = renderer.ConvertToPDF(wordDocument);

        using FileStream output = new FileStream(outputPath, FileMode.Create, FileAccess.Write);
        pdf.Save(output);
        pdf.Close(true);
        wordDocument.Close();

        await Task.CompletedTask;
    }
}
