using Gremlin.GremlinUtilities;
using System;
using System.Diagnostics;
using System.IO;

namespace Gremlin.Operations
{
    internal class PDFHandler
    {
        public static void CreatePDF(string fileName, string quotePath)
        {
            //Copy images to quotePath
            File.WriteAllBytes($"{quotePath}\\agilentLogo.png", Properties.Resources.agilentLogo);
            File.WriteAllBytes($"{quotePath}\\signWoitschetzki.png", Properties.Resources.signWoitschetzki);

            //Create PDF twice
            RunningPDFLaTeX(quotePath, fileName, 2);

            //CleanUp
            //RemoveTempFiles(quotePath);

            //OpenPDF
            //FileIO.OpenFile(quotePath, fileName, "pdf");
        }

        public static void RemoveTempFiles(string quotePath)
        {
            DirectoryInfo directoryInfo = new(AppDomain.CurrentDomain.BaseDirectory);
            foreach (FileInfo file in directoryInfo.EnumerateFiles())
            {
                if (file.Extension is ".aux" or ".out" or ".log")
                {
                    try
                    {
                        file.Delete();
                    }
                    catch (Exception ex)
                    {
                        ErrorHandler.ShowErrorInMessageBox(ex);
                    }
                }
                //if (file.Extension is ".pdf" or ".tex")
                //{
                //    try
                //    {
                //        File.Move(file.ToString(), quotePath);
                //    }
                //    catch (Exception ex)
                //    {
                //        ErrorHandler.ShowErrorInMessageBox(ex);
                //    }
                //}
            }
        }

        private static void RunningPDFLaTeX(string quotePath, string fileName, int runs)
        {
            for (int i = 0; i < runs; i++)
            {
                using (Process process = new())
                {
                    process.StartInfo.FileName = "pdflatex";
                    process.StartInfo.Arguments = quotePath == "" ? $"{fileName}.tex" : $"{quotePath}\\{fileName}.tex";
                    process.StartInfo.UseShellExecute = false;
                    try
                    {
                        _ = process.Start();
                    }
                    catch (Exception ex)
                    {
                        ErrorHandler.ShowErrorInMessageBox(ex);
                    }
                    process.WaitForExit();
                }
            }
        }
    }
}
