using System.Collections.Concurrent;
using Aspose.Pdf;

namespace Fast.Logic;

public static partial class Util
{
    public static class Pdf
    {
        public static MemoryStream CombinePdfs(List<Tuple<string, string>> fileDescriptorsAndPaths)
        {
            ConcurrentDictionary<string, Document> pdfDocs = new();

            Parallel.ForEach(fileDescriptorsAndPaths, descriptorPathPair =>
            {
                string descriptor = descriptorPathPair.Item1;
                string filePath = descriptorPathPair.Item2;
                if (System.IO.File.Exists(filePath))
                    pdfDocs.TryAdd(filePath, new Document(filePath));
                else
                    throw new Exception($"File not found for {descriptor}, {filePath}");
            });

            if (!pdfDocs.Any())
                throw new Exception("Files not found");

            Document combinedDoc;

            if (pdfDocs.Count > 1)
            {
                combinedDoc = new Document();
                foreach (var descriptorPathPair in fileDescriptorsAndPaths)
                {
                    string filePath = descriptorPathPair.Item2;
                    if (pdfDocs.ContainsKey(filePath))
                    {
                        Document doc = pdfDocs[filePath];
                        combinedDoc.Pages.Add(doc.Pages);
                    }
                }
            }
            else
            {
                combinedDoc = pdfDocs.First().Value;
            }

            MemoryStream stream = new();
            combinedDoc.Save(stream, SaveFormat.Pdf);
            stream.Seek(0, SeekOrigin.Begin);

            return stream;
        }
    }
}
