using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Volian.Print.Library;
using VEPROMS.CSLA.Library;
using Volian.Base.Library;

namespace VEPROMS
{
	public partial class frmPDFStatusForm : Form
	{
		private bool _CancelPrinting = false;
		public bool CancelPrinting
		{
			get { return _CancelPrinting; }
			set { _CancelPrinting = value; }
		}
		private bool _CloseWhenDone = false;
		public bool CloseWhenDone
		{
			get { return _CloseWhenDone; }
			set { _CloseWhenDone = value; }
		}
		private bool _CancelStop = false;
		public bool CancelStop
		{
			get { return _CancelStop; }
			set { _CancelStop = value; }
		}
		private bool _Stop = false;
		public bool Stop
		{
			get { return _Stop; }
			set { _Stop = value; }
		}
		private string _PDFPath;

		public string PDFPath
		{
			get { return _PDFPath; }
			set { _PDFPath = value; }
		}
		private PromsPrinter _MyPromsPrinter;

		public PromsPrinter MyPromsPrinter
		{
			get { return _MyPromsPrinter; }
			set { _MyPromsPrinter = value; }
		}

		private bool _OpenPDF;

		public bool OpenPDF
		{
			get { return _OpenPDF; }
			set { _OpenPDF = value; }
		}
		private Point _NewLocation;
		private string _Prefix = ""; // RHM20150506 Multiline ItemID TextBox
		public string Prefix
		{
			get { return _Prefix; }
			set { _Prefix = value; }
		}
		// this flag is used when the Continuous Action Sumamry is printed from the tree or ribbon button
		// it will prevent the temporary PDF (generated with printing - needed to get page numbers) from being displayed
		// and will delete that temporary PDF file
		private bool _OnlyShowContinuousActionSummary = false;
		public bool OnlyShowContinuousActionSummary
		{
			get { return _OnlyShowContinuousActionSummary; }
			set { _OnlyShowContinuousActionSummary = value; }
		}
		public frmPDFStatusForm(ItemInfo myItem, string rev, string watermark, bool debugOutput, bool origPgBrk, bool openPDF, bool overWrite, string pdfPath, ChangeBarDefinition cbd,string pdfFile, Point newLocation,bool insertBlankPages, bool allOrAuto, string prefix, bool saveLinks, bool removeTrailingHardReturnsAndManualPageBreaks)
		{
			Prefix = prefix;
			OpenPDF = openPDF;
			InitializeComponent();
			// if the version number of PROMS is 1.0, then we are running a Demo version.
			// When running a Demo version, force a "Sample" watermark when printing.
			MyPromsPrinter = new PromsPrinter(myItem, rev, (VlnSettings.ReleaseMode.Equals("DEMO")) ? "Sample" : watermark, debugOutput, origPgBrk, pdfPath + @"\\Compare", false, overWrite, cbd, pdfFile, insertBlankPages, allOrAuto,Prefix,saveLinks,removeTrailingHardReturnsAndManualPageBreaks);
			PDFPath = pdfPath;
			this.Text = "Creating PDF of " + myItem.DisplayNumber;
			_NewLocation = newLocation;
			DialogResult = DialogResult.OK;
		}
		// used when the approved function creates an export file with unlinked ROs and Transitons.  Word sections that have RO tokens are saved with the RO Vaules in DocReplace
		// DocReplace is passed on to the Export functions.
		private Dictionary<int, byte[]> _DocReplace;
		public Dictionary<int, byte[]> DocReplace
		{
			get { return _DocReplace; }
			set { _DocReplace = value; }
		}
		public bool AllowAllWatermarks
		{
			get { return MyPromsPrinter.AllowAllWatermarks; }
			set { MyPromsPrinter.AllowAllWatermarks = value; }
		}
		void pp_StatusChanged(object sender, PromsPrintStatusArgs args)
		{
			if (args.Type == PromsPrinterStatusType.ProgressSetup)
				pb.Maximum = args.Progress;
			else if (args.Type == PromsPrinterStatusType.Progress)
			{
				pb.Value = args.Progress;
				if (args.Progress == pb.Maximum)
					pb.Text = args.MyStatus;
				else
					pb.Text = string.Format("Processing {0} ({1} of {2})", args.MyStatus, args.Progress + 1, pb.Maximum);
			}
			MyStatus = args.MyStatus;
			Application.DoEvents();
		}
		public string MyStatus
		{
			get { return lblStatus.Text; }
			set { lblStatus.Text = value; Application.DoEvents(); }
		}

		private void frmPDFStatusForm_Load(object sender, EventArgs e)
		{
			Location = _NewLocation;
			tmrRun.Enabled = true;
			if (MakeContinuousActionSummary)
				Text = Text.Replace("PDF", "Continuous Action Summary");
		}

		private string _PdfFile;

		private bool _MakePlaceKeeper = false;

		public bool MakePlaceKeeper
		{
			get { return _MakePlaceKeeper; }
			set { _MakePlaceKeeper = value; }
		}

		private bool _MakeContinuousActionSummary = false;

		public bool MakeContinuousActionSummary
		{
			get { return _MakeContinuousActionSummary; }
			set { _MakeContinuousActionSummary = value; }
		}

		private void tmrRun_Tick(object sender, EventArgs e)
		{
			tmrRun.Enabled = false;
			if (CancelStop) btnCancel.Visible = true;
			Application.DoEvents();
			MyPromsPrinter.StatusChanged += new PromsPrinterStatusEvent(pp_StatusChanged);
			MyPromsPrinter.DocReplace = DocReplace;  // used when approve generates an export with unlinked ROs and Transitions
			DateTime tStart = DateTime.Now;
			if (!CancelStop) PromsPrinter.ClearTransPageNumProblems();
			do
			{
				int profileDepth = ProfileTimer.Push(">>>> MyPromsPrinter.Print");
				_PdfFile = MyPromsPrinter.Print(PDFPath, MakePlaceKeeper, MakeContinuousActionSummary);
				ProfileTimer.Pop(profileDepth);
			}
			while (_PdfFile == null && MessageBox.Show("Try Again?", "PDF Creation Failed", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes);
			if (_PdfFile == null)
			{
				this.Close();
				return;
			}
			if (!CancelStop)
			{
				if (PromsPrinter.ReportTransPageNumProblems() == DialogResult.Yes && MyPromsPrinter.BeforePageNumberPdf != null)
				{
					System.Diagnostics.Process.Start(MyPromsPrinter.BeforePageNumberPdf);
					// C2017-018 - Open Pass 2 output if it exists
					if (MyPromsPrinter.BeforePageNumber2Pdf != null) System.Diagnostics.Process.Start(MyPromsPrinter.BeforePageNumber2Pdf);
				}
			}
			DateTime tEnd = DateTime.Now;
			MyStatus = _PdfFile + " created.";
			MyStatus = string.Format("{0} created in {1:0.} milliseconds", _PdfFile, (TimeSpan.FromTicks(tEnd.Ticks - tStart.Ticks).TotalMilliseconds));
			if (OpenPDF)
			{
				OpenPDFandPlacekeeper(_PdfFile);
				this.Close();
				return;
			}
			btnOpenFolder.Visible = btnOpenPDF.Visible = true;
			
			if (CloseWhenDone)
			{
				OpenPDFandPlacekeeper(null);
				this.Close();
				return;
			}
		}
		private void btnOpenPDF_Click(object sender, EventArgs e)
		{
			OpenPDFandPlacekeeper(_PdfFile);
			this.Close();
		}
		// set a delay so that the word document containing the newly generated placekeeper will appear on top of everything else.
		// - requested by Calvert Cliffs
		private void OpenPDFandPlacekeeper(string pdffile)
		{
			if ((pdffile ?? "") != "" && !OnlyShowContinuousActionSummary)
			{
				System.Diagnostics.Process sdp = System.Diagnostics.Process.Start(pdffile);
				sdp.WaitForInputIdle();
			}
			if (OnlyShowContinuousActionSummary)
				System.IO.File.Delete(pdffile); // remove the temporary PDF file used to create the Continuous Action Summary
			if (MyPromsPrinter.MyPlacekeeper != null)
			{
				// The PlacekeeperDelay is a switch that can be added to the PROMS.exe shortcut
				// ex: VEPROMS.EXE /PlacekeeperDelay=2.5 will delay it 2 1/2 seconds
				float delay = Volian.Base.Library.VlnSettings.GetCommandFloat("PlacekeeperDelay", 3.0f);
				int mydelay =(int) (1000 * delay);
				System.Threading.Thread.Sleep(mydelay);
				MyPromsPrinter.MyPlacekeeper.Visible();
			}
			// this will display the generated Continuous Action Summary in MS Word (starting a new instance of MS Word outside of PROMS)
			if (MyPromsPrinter.MyContActSummary != null)
			{
				string instructions = "The Continuous Action Summary will be opened in MS Word.\n\nYou can make modifications and copy it into a PROMS Word section.";
				MessageBox.Show(instructions, "Continuous Action Summary");
				// The ContActSummaryDelay is a switch that can be added to the PROMS.exe shortcut
				// ex: VEPROMS.EXE /ContActSummaryDelay=2.5 will delay it 2 1/2 seconds
				float delay = Volian.Base.Library.VlnSettings.GetCommandFloat("ContActSummaryDelay", 1.0f);
				int mydelay = (int)(1000 * delay);
				System.Threading.Thread.Sleep(mydelay);
				MyPromsPrinter.MyContActSummary.Visible();
			}

		}
		private void btnOpenFolder_Click(object sender, EventArgs e)
		{
			System.Diagnostics.Process.Start("Explorer", "/select," + _PdfFile);
			OpenPDFandPlacekeeper(null);
			this.Close();
		}
		private void btnCancel_Click(object sender, EventArgs e)
		{
			CancelPrinting = true;
			btnCancel.Text = "Cancelled";
			btnCancel.Enabled = false;
		}
	}
}