using Gremlin.MVVM.ViewModels;
using System;
using System.Diagnostics;
using System.IO;

namespace Gremlin.GremlinUtilities
{
	internal class PDFHandler
	{
		public static bool CreatePDF(QuoteViewModel quoteVM)
		{
			//Copy images to quotePath
			try
			{
				if (quoteVM.QuotePath is "" or null)
				{
					File.WriteAllBytes("agilentLogo.png", Properties.Resources.agilentLogo);
					File.WriteAllBytes("signWoitschetzki.png", Properties.Resources.signWoitschetzki);
				}
				else
				{
					File.WriteAllBytes($"{quoteVM.QuotePath}agilentLogo.png", Properties.Resources.agilentLogo);
					File.WriteAllBytes($"{quoteVM.QuotePath}signWoitschetzki.png", Properties.Resources.signWoitschetzki);
				}

				//Create PDF twice
				RunningPDFLaTeX(quoteVM, 2);
				RemoveTempFiles(quoteVM.QuotePath);
				return true;
			}
			catch (Exception ex)
			{
				ErrorHandler.ShowErrorInMessageBox(ex);
				return false;
			}
		}

		public static void RemoveTempFiles(string quotePath)
		{
			DirectoryInfo directoryInfo = new(quotePath);

			foreach (FileInfo file in directoryInfo.EnumerateFiles())
			{
				if (file.Extension is ".aux" or ".out" or ".log") // or ".png") #let pngs left
				{
					try
					{
						file.Delete();
						//Console.WriteLine($"{file.FullName} wurde gelöscht.");
					}
					catch (Exception ex)
					{
						ErrorHandler.ShowErrorInMessageBox(ex);
					}
				}
			}
		}

		private static void RunningPDFLaTeX(QuoteViewModel quoteVM, int runs)
		{
			for (int i = 0; i < runs; i++)
			{
				using (Process process = new())
				{
					process.StartInfo.WorkingDirectory = quoteVM.QuotePath;
					process.StartInfo.FileName = "pdflatex";
					process.StartInfo.Arguments = quoteVM.QuoteNumber;
					process.StartInfo.UseShellExecute = true;

					try
					{
						_ = process.Start();
					}
					catch (Exception ex)
					{
						ErrorHandler.ShowErrorInMessageBox(ex);
					}

					process.WaitForExit();
				}
			}
		}

		public static bool OpenPDF(QuoteViewModel quoteVM)
		{
			using (Process process = new())
			{
				process.StartInfo.WorkingDirectory = quoteVM.QuotePath;
				process.StartInfo.FileName = @"C:\Program Files\Okular\bin\okular.exe";
				process.StartInfo.Arguments = $"{quoteVM.QuoteNumber}.pdf";
				try
				{
					return process.Start();
				}
				catch (Exception ex)
				{
					ErrorHandler.ShowErrorInMessageBox(ex);
					return false;
				}
			}
		}
	}
}
