using lib;
using lib.model;
using OfficeOpenXml;
using OfficeOpenXml.FormulaParsing.Excel.Functions.DateTime;
using OfficeOpenXml.FormulaParsing.Excel.Functions.Math;
using Packing.lib;
using Packing.lib.datasource;
using Patagames.Pdf.Net;
using Patagames.Pdf.Net.Controls.WinForms;
using PdfSharp;
using PdfSharp.Drawing;
using PdfSharp.Pdf;
using PdfSharp.Pdf.Printing;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Drawing.Printing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using TheArtOfDev.HtmlRenderer.PdfSharp;

namespace Packing
{
    public partial class ReprintFrm : Form
    {
        const string INI = "Packing.ini";
        private string printerName;
        string selected_preset;
        private string qty;
        private string pdfPath;
        private System.Drawing.Printing.PrintDocument printDocument;
        public static IniFile ini = new IniFile(INI);
        TextProcessing textProcessing;
        private static char delimiter = ini.Read("Delimiter", "Reader").ToCharArray()[0];
        private string printBuffer;

        public ReprintFrm()
        {
            InitializeComponent();
            this.printDocument = new System.Drawing.Printing.PrintDocument();
            this.printDocument.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(this.ThePrintDocument_PrintLabel);

            //Initialize text processing
            string input_format = ini.Read("input", selected_preset);
            //char delimiter = ini.Read("Delimiter", null).ToCharArray()[0];
            textProcessing = new TextProcessing(input_format, delimiter);
        }

        private void ReprintFrm_Load(object sender, EventArgs e)
        {
            txtPalletSerialNumber.Text = string.Empty;
            pdfPath = "C:\\Program Files\\Adobe\\Acrobat DC\\Acrobat\\Acrobat.exe";
            pdfPath = ini.Read("PDF", "Packing").ToString();

            List<object[]> rows_Reprint_data = LeakTestCodeDs.GetRelatedReprintData();

            ReprintDs.list = new List<ReprintDs>();

            Int32 i = 1;

            foreach (object[] row in rows_Reprint_data)
            {
                // go to each record of reprint

                ReprintDs.list.Add(new ReprintDs(i.ToString(), row[0].ToString(), row[1].ToString()));

                i++;

            }

            dataGridReprintList.DataSource = ReprintDs.list;

            dataGridReprintList.Columns[0].Width = 150;
            dataGridReprintList.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
            dataGridReprintList.Columns[2].Width = 300;

            dataGridReprintList.Columns[1].HeaderText = "Pallet serial number";
            dataGridReprintList.Columns[2].HeaderText = " Inspection date";

            dataGridReprintList.Columns[1].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft;

        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void dataGridReprintList_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            //var grid = sender as DataGridView;
            //var rowIdx = (e.RowIndex + 1).ToString();

            //var centerFormat = new StringFormat()
            //{
            //    // right alignment might actually make more sense for numbers
            //    Alignment = StringAlignment.Center,
            //    LineAlignment = StringAlignment.Center
            //};

            //var headerBounds = new Rectangle(e.RowBounds.Left, e.RowBounds.Top, grid.RowHeadersWidth, e.RowBounds.Height);
            //e.Graphics.DrawString(rowIdx, this.Font, SystemBrushes.ControlText, headerBounds, centerFormat);

        }

        private void dataGridReprintList_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void dataGridReprintList_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0)
            {
                return;
            }
            txtPalletSerialNumber.Text = (dataGridReprintList.Rows[e.RowIndex].Cells[1]).Value.ToString();

        }

        private void btnReprint_Click(object sender, EventArgs e)
        {
            List<object[]> rows = LeakTestCodeDs.GetRelatedReprintDataSelect(txtPalletSerialNumber.Text.Trim());

            if (rows.Count > 0)
            {
                Cursor = Cursors.WaitCursor;

                LeakTestCodeDs.ReprintPalletSerialNo = rows[0][0].ToString();
                LeakTestCodeDs.ReprintPrintDate = rows[0][1].ToString();
                LeakTestCodeDs.ReprintPartNo = rows[0][2].ToString();
                LeakTestCodeDs.ReprintPartCode = rows[0][3].ToString();
                LeakTestCodeDs.ReprintPartName = rows[0][4].ToString();
                LeakTestCodeDs.ReprintAbbreviation = rows[0][5].ToString();
                LeakTestCodeDs.ReprintSerialNo = rows[0][6].ToString();
                LeakTestCodeDs.ReprintInspectionDate = rows[0][7].ToString();
                LeakTestCodeDs.ReprintQty = rows[0][8].ToString();
                LeakTestCodeDs.ReprintUserName = rows[0][9].ToString();


                LeakTestCodeDs.ReprintInspectionDate = LeakTestCodeDs.ReprintInspectionDate.Substring(8, 2) + "/" +
                    LeakTestCodeDs.ReprintInspectionDate.Substring(5, 2) + "/" + LeakTestCodeDs.ReprintInspectionDate.Substring(0, 4);

                string[] arrayAbbreviation;
                string strAbbreviation1 = string.Empty;
                string strAbbreviation2 = string.Empty;
                string strAbbreviation3 = string.Empty;
                string[] arraySerial_no = new string[48];
                string strSerial_no011 = string.Empty;
                string strSerial_no012 = string.Empty;
                string strSerial_no013 = string.Empty;


                arrayAbbreviation = LeakTestCodeDs.ReprintAbbreviation.Split('/');

                if (arrayAbbreviation.Length == 3)
                {
                    strAbbreviation1 = arrayAbbreviation[0];
                    strAbbreviation2 = arrayAbbreviation[1];
                    strAbbreviation3 = arrayAbbreviation[2];
                }
                else if (arrayAbbreviation.Length == 2)
                {
                    strAbbreviation1 = arrayAbbreviation[0];
                    strAbbreviation2 = arrayAbbreviation[1];
                    strAbbreviation3 = string.Empty;
                }
                else if (arrayAbbreviation.Length == 1)
                {
                    strAbbreviation1 = arrayAbbreviation[0];
                    strAbbreviation2 = string.Empty;
                    strAbbreviation3 = string.Empty;
                }

                arraySerial_no = LeakTestCodeDs.ReprintSerialNo.Split('|');
               
                strSerial_no011 = arraySerial_no[0];
                strSerial_no012 = arraySerial_no[1];
                strSerial_no013 = arraySerial_no[2];
                

                if (strSerial_no011.Trim().Length == 0)
                {
                    strSerial_no011 = " color:White;\">_________________";
                }
                else
                {
                    strSerial_no011 = " \">" + arraySerial_no[0];
                }

                if (strSerial_no012.Trim().Length == 0)
                {
                    if (strSerial_no011.Trim().Length == 19)
                    {
                        strSerial_no012 = " color:White;\">_________________";
                    }
                    else
                    {
                        strSerial_no012 = " color:White;\">________________";
                    }

                }
                else
                {
                    strSerial_no012 = " \">" + arraySerial_no[1];
                }

                if (strSerial_no013.Trim().Length == 0)
                {
                    if (strSerial_no011.Trim().Length == 19)
                    {
                        strSerial_no013 = " color:White;\">_________________";
                    }
                    else
                    {
                        strSerial_no013 = " color:White;\">________________";
                    }
                }
                else
                {
                    strSerial_no013 = " \">" + arraySerial_no[2];
                }


                printLabel(sender, e, LeakTestCodeDs.ReprintPalletSerialNo + "|" + LeakTestCodeDs.ReprintPartCode + "|" + LeakTestCodeDs.ReprintPartName + "|"
                    + LeakTestCodeDs.ReprintInspectionDate + "|" + LeakTestCodeDs.ReprintQty + "|" + strAbbreviation1 + "|"
                    + strAbbreviation2 + "|" + strAbbreviation3 + "|" + LeakTestCodeDs.ReprintUserName + "|"
                    + strSerial_no011 + "|" + strSerial_no012 + "|" + strSerial_no013 + "|"
                    + arraySerial_no[3] + "|" + arraySerial_no[4] + "|" + arraySerial_no[5] + "|"
                        + arraySerial_no[6] + "|" + arraySerial_no[7] + "|" + arraySerial_no[8] + "|"
                        + arraySerial_no[9] + "|" + arraySerial_no[10] + "|" + arraySerial_no[11] + "|"
                        + arraySerial_no[12] + "|" + arraySerial_no[13] + "|" + arraySerial_no[14] + "|"
                        + arraySerial_no[15] + "|" + arraySerial_no[16] + "|" + arraySerial_no[17] + "|"
                        + arraySerial_no[18] + "|" + arraySerial_no[19] + "|" + arraySerial_no[20] + "|"
                        + arraySerial_no[21] + "|" + arraySerial_no[22] + "|" + arraySerial_no[23] + "|"
                        + arraySerial_no[24] + "|" + arraySerial_no[25] + "|" + arraySerial_no[26] + "|"
                        + arraySerial_no[27] + "|" + arraySerial_no[28] + "|" + arraySerial_no[29] + "|"
                        + arraySerial_no[30] + "|" + arraySerial_no[31] + "|" + arraySerial_no[32] + "|"
                        + arraySerial_no[33] + "|" + arraySerial_no[34] + "|" + arraySerial_no[35] + "|"
                        + arraySerial_no[36] + "|" + arraySerial_no[37] + "|" + arraySerial_no[38] + "|"
                        + arraySerial_no[39] + "|" + arraySerial_no[40] + "|" + arraySerial_no[41] + "|"
                        + arraySerial_no[42] + "|" + arraySerial_no[43] + "|" + arraySerial_no[44] + "|"
                        + arraySerial_no[45] + "|" + arraySerial_no[46] + "|" + arraySerial_no[47]
                       
                );

                Cursor = Cursors.Default;

            }
            else
            {
                LeakTestCodeDs.ReprintPalletSerialNo = null;
                LeakTestCodeDs.ReprintPrintDate = null;
                LeakTestCodeDs.ReprintPartNo = null;
                LeakTestCodeDs.ReprintPartCode = null;
                LeakTestCodeDs.ReprintPartName = null;
                LeakTestCodeDs.ReprintAbbreviation = null;
                LeakTestCodeDs.ReprintSerialNo = null;
                LeakTestCodeDs.ReprintInspectionDate = null;
                LeakTestCodeDs.ReprintQty = null;
                LeakTestCodeDs.ReprintUserName = null;

                Form ngFrm = new NgFrm("No print data NG!!", "History print not found.");
                ngFrm.ShowDialog();
                return;

            }

        }

        private void printLabel(object sender, EventArgs e, string strprintBuffer)
        {
            //ini.Write("printer", printerName, selected_preset);
            printerName = ini.Read("printer", selected_preset);
            qty = ini.Read("qty", selected_preset);
            //ini.Write("template", System.IO.Directory.GetCurrentDirectory() + "\\Template-Packing.html", selected_preset);
            //ini.Write("width", "800", selected_preset);
            //ini.Write("height", "2000", selected_preset);

            //Print Label
            if (setContentPrintBuffer(strprintBuffer))
            {
                var config = new PdfGenerateConfig();
                config.PageOrientation = PageOrientation.Landscape;
                config.PageSize = PageSize.A4;

                PdfSharp.Pdf.PdfDocument pdf = PdfGenerator.GeneratePdf(printBuffer, config);
                pdf.Save("document_new.pdf");

                PrintPdf();

                //printDocument.PrinterSettings.PrinterName = this.printerName;
                //printDocument.PrinterSettings.Copies = Convert.ToInt16(qty);
                //printDocument.DefaultPageSettings.Landscape = true;

                //printDocument.Print();
            }
        }


        private bool setContentPrintBuffer(string str)
        {
            bool ret = true;
            //Dictionary<string, VarObject> vars = textProcessing.ParseInput(str, '|');
            Dictionary<string, VarObject> vars = textProcessing.ParseInput(str, delimiter);


            foreach (string key in vars.Keys)
            {
                VarObject v;
                vars.TryGetValue(key, out v);
            }

            //Read template content
            try
            {
                string html = System.IO.File.ReadAllText(ini.Read("template", selected_preset));

                //Process html
                html = TextProcessing.ReplaceVariables(textProcessing, html, ini);

                printBuffer = html;
            }
            catch (Exception e)
            {
                //log("Error: " + e.Message);
                ret = false;

            }

            return ret;
        }

        protected void ThePrintDocument_PrintLabel(object sender, System.Drawing.Printing.PrintPageEventArgs ev)
        {
            SolidBrush myBrush = new SolidBrush(Color.Black);

            string strwidth = ini.Read("width", selected_preset);
            string strheight = ini.Read("height", selected_preset);
            Int32 Intwidth = Convert.ToInt32(strwidth);
            Int32 Intheight = Convert.ToInt32(strheight);

            //HTML render
            Image image = TheArtOfDev.HtmlRenderer.WinForms.HtmlRender.RenderToImage(printBuffer);
      
            ev.Graphics.CompositingQuality = CompositingQuality.HighQuality;
            ev.Graphics.SmoothingMode = SmoothingMode.HighQuality;
            ev.Graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;

            Rectangle rect = new Rectangle(0, 0, Intwidth, Intheight); // (0, 0, Wide, High)

            ev.Graphics.DrawImage(image, rect);

            ev.HasMorePages = false;

            myBrush.Dispose();
        }

        public void PrintPdf()
        {
            //var doc = Patagames.Pdf.Net.PdfDocument.Load("document_new.pdf");
            //var printDoc = new PdfPrintDocument(doc);
            //PrintController printController = new StandardPrintController();
            //printDoc.PrintController = printController;
            //printDoc.PrinterSettings.PrinterName = this.printerName;
            //printDoc.PrinterSettings.Copies = Convert.ToInt16(qty);
            //printDoc.DefaultPageSettings.Landscape = true;
            //printDoc.Print(); // Print PDF document
            //doc.Dispose();

            PdfFilePrinter.AdobeReaderPath = pdfPath;
      //= @"C:\Program Files\Adobe\Acrobat DC\Acrobat\Acrobat.exe";
            //PdfFilePrinter.DefaultPrinterName = this.printerName;           
            PdfFilePrinter printer = new PdfFilePrinter("document_new.pdf");
            printer.PrinterName = this.printerName;

            for (int i = 0; i < Convert.ToInt16(qty); i++)
            {

                printer.Print(5000);

            }

            Thread.Sleep(6000);

            FindAndKillProcess("Acrobat");

        }

        public bool FindAndKillProcess(string name)
        {
            //here we're going to get a list of all running processes on
            //the computer
            foreach (Process clsProcess in Process.GetProcesses())
            {
                //now we're going to see if any of the running processes
                //match the currently running processes by using the StartsWith Method,
                //this prevents us from incluing the .EXE for the process we're looking for.
                //. Be sure to not
                //add the .exe to the name you provide, i.e: NOTEPAD,
                //not NOTEPAD.EXE or false is always returned even if
                //notepad is running
                if (clsProcess.ProcessName.Contains(name))
                {
                    //since we found the proccess we now need to use the
                    //Kill Method to kill the process. Remember, if you have
                    //the process running more than once, say IE open 4
                    //times the loop thr way it is now will close all 4,
                    //if you want it to just close the first one it finds
                    //then add a return; after the Kill
                    clsProcess.Kill();
                    //process killed, return true
                    return true;
                }
            }
            //process not found, return false
            return false;
        }

    }
}
