using System;
using System.IO;
using Spire.Pdf;

namespace AdvertsingProfitControl
{
    internal class ReportGenerator
    {
        public static readonly string Version = "0.5.0.0";

        /// <summary>
        /// Generates a full report, and places the file on the user's desktop for later viewing.
        /// </summary>
        /// <param name="date"></param>
        public void GeneratePdfReport(DateTime date)
        {
            //Check to see if the report already exists.
            var reportFileName = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\" + date.ToString("yyyy MMMM dd") + " Report.pdf";
            if (File.Exists(reportFileName))
            {
                var argument = "/select, \"" + reportFileName + "\"";
                System.Diagnostics.Process.Start("explorer.exe", argument);
                return;
            }
            var front = new FrontPageGenerator();
            var back = new BackPageGenerator();
            front.GenerateFrontPage(date);
            back.GenerateBackPage(date);
            //Merge the PDFs
            GenerateFullReport(reportFileName);
        }
        /// <summary>
        /// Merges the front and back PDF files into one and places the new file on the user's desktop.
        /// Deletes the front and back pages when done.
        /// </summary>
        /// <param name="targetPath"></param>
        private static void GenerateFullReport(string targetPath)
        {
            try
            {
                var pdfdocs = new PdfDocument[2];
                pdfdocs[0] = new PdfDocument();
                pdfdocs[0].LoadFromFile(GlobalClasses.LogFilePath + "Front.pdf", FileFormat.PDF);
                pdfdocs[1] = new PdfDocument();
                pdfdocs[1].LoadFromFile(GlobalClasses.LogFilePath + "Back.pdf", FileFormat.PDF);
                pdfdocs[0].AppendPage(pdfdocs[1]);
                pdfdocs[0].SaveToFile(targetPath);
                pdfdocs[0].Close();
                pdfdocs[1].Close();
                File.Delete(GlobalClasses.LogFilePath + "Front.pdf");
                File.Delete(GlobalClasses.LogFilePath + "Back.pdf");
                var argument = "/select, \"" + targetPath + "\"";
                System.Diagnostics.Process.Start("explorer.exe", argument);
            }
            catch (IOException e)
            {
                
            }
            finally
            {

            }
        }
    }
}
