using System.Text;
using KiMailOrderAgent.Models;

namespace KiMailOrderAgent.Attachments;

public class AttachmentTextExtractor : IAttachmentTextExtractor
{
    private readonly PdfTextExtractor _pdfTextExtractor = new();
    private readonly OdfTextExtractor _odfTextExtractor = new();
    private readonly DocxTextExtractor _docxTextExtractor = new();

    public Task<string> ExtractTextAsync(MailAttachment attachment, CancellationToken cancellationToken)
    {
        var fileName = attachment.FileName.ToLowerInvariant();

        try
        {
            if (fileName.EndsWith(".txt"))
                return Task.FromResult(Encoding.UTF8.GetString(attachment.Content));

            if (fileName.EndsWith(".pdf"))
                return Task.FromResult(_pdfTextExtractor.Extract(attachment.Content));

            if (fileName.EndsWith(".odt") || fileName.EndsWith(".ods"))
                return Task.FromResult(_odfTextExtractor.Extract(attachment.Content));

            if (fileName.EndsWith(".docx"))
                return Task.FromResult(_docxTextExtractor.Extract(attachment.Content));
        }
        catch
        {
            return Task.FromResult("");
        }

        return Task.FromResult("");
    }
}