using System;
using System.Data.SQLite;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;

namespace BulkPrinting
{
    public partial class PrintAlignmentDialog : Form
    {
        public PrintAlignmentDialog()
        {
            InitializeComponent();
        }

        public string PrintDescription;
        public DateTime BatchOrderDate;
        public string FaceValue;
        public string VoucherTypeName;
        public string NetworkName;
        public int BatchID;
        public int? NumVouchers;
        public int? FirstSeqNo;
        public int? LastSeqNo;

        private bool expanded;
        int minHeight;
        int maxHeight;

        private void PrintAlignmentDialog_Load(object sender, EventArgs e)
        {
            var btnExpandScreenRectangle = btnExpand.Parent.RectangleToScreen(btnExpand.Bounds);
            var grpAlignmentScreenRectangle = grpAlignment.Parent.RectangleToScreen(grpAlignment.Bounds);

            minHeight = btnExpandScreenRectangle.Bottom - Bounds.Top + 10;
            maxHeight = grpAlignmentScreenRectangle.Bottom - Bounds.Top + 10;

            Height = minHeight;

            grpAlignment.Show();
            lblBusyPrinting.Hide();

            lblPrintDescription.Text = "Ready to Print: ";
            if (FirstSeqNo != null && LastSeqNo != null) {
                lblPrintDescription.Text += "Vouchers numbered " + FirstSeqNo.ToString() + " to " + LastSeqNo.ToString() + "\nFrom Batch \"" + PrintDescription+"\"";
            }
            else if (NumVouchers != null) {
                lblPrintDescription.Text += NumVouchers.ToString() + " Vouchers\nFrom Batch \"" + PrintDescription + "\"";
            }

            lblBatchNumber.Text = BatchID.ToString();
            lblBatchOrderDate.Text = BatchOrderDate.Date.ToString("dd/MM/yyyy");
            lblFaceValue.Text = FaceValue;
            lblVoucherType.Text = VoucherTypeName;
            lblNetwork.Text = NetworkName;
        }

        private void btnAlignment_Click(object sender, EventArgs e)
        {

            var PrinterInitString = Utility.GetPrinterInitString(Globals.DB);
            int initJobID = Globals.MaxPrinter.Open("Printer_Init");
            if (initJobID == 0) return;
            Globals.MaxPrinter.Print(PrinterInitString.ToString());
            //Globals.MaxPrinter.Print(Printer.INITIALISE_PRINTER);
            //Globals.MaxPrinter.Print(Printer.UNIDIRECTIONAL_OFF);
            //Globals.MaxPrinter.Print(Printer.CHARPITCHELITE);
            //Globals.MaxPrinter.Print(Printer.EMPHASISE_ON);
            //Globals.MaxPrinter.Close();


            //if (Globals.MaxPrinter.Open("Alignment")==0) return;

            string AlignmentPage ="";

            for (var i = 0; i < 8; i++) //Two full pages of vouchers
            {
                //AlignmentPage += "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\r\n";
                
                AlignmentPage += "\r\n\n\n" +
                "[--VOUCHER  PIN  CODE--]      [--VOUCHER  PIN  CODE--]      [--VOUCHER  PIN  CODE--]       [--VOUCHER  PIN  CODE--]      [--VOUCHER  PIN  CODE--]\r\n\n" +
                "[--VOUCHER SERIAL NUM--]      [--VOUCHER SERIAL NUM--]      [--VOUCHER SERIAL NUM--]       [--VOUCHER SERIAL NUM--]      [--VOUCHER SERIAL NUM--]\r\n" +
                "[--BATCHNO/SEQNO/PAGE--]      [--BATCHNO/SEQNO/PAGE--]      [--BATCHNO/SEQNO/PAGE--]       [--BATCHNO/SEQNO/PAGE--]      [--BATCHNO/SEQNO/PAGE--]\r\n" +
                "[--VOUCHERDESCRIPTION--]      [--VOUCHERDESCRIPTION--]      [--VOUCHERDESCRIPTION--]       [--VOUCHERDESCRIPTION--]      [--VOUCHERDESCRIPTION--]\r\n" +
                "[--VENDOR          ID--]      [--VENDOR          ID--]      [--VENDOR          ID--]       [--VENDOR          ID--]      [--VENDOR          ID--]\r\n\n\n\n\n\n\n\n\n\n";
            }
            
            Globals.MaxPrinter.Print(AlignmentPage);
            Globals.MaxPrinter.Close();
        }

        private void btnPrintJob_Click(object sender, EventArgs e)
        {
            int FirstVoucherSequenceNumber;
            int LastVoucherSequenceNumber;


            if (FirstSeqNo != null && LastSeqNo != null)
            {
                FirstVoucherSequenceNumber = (int)FirstSeqNo;
                LastVoucherSequenceNumber = (int)LastSeqNo;
            }
            else if (NumVouchers != null)
            {
                FirstVoucherSequenceNumber = Convert.ToInt32(Globals.DB.ExecuteScalar(
                    "SELECT MIN(v.SequenceNumber) FROM Voucher v " +
                        "LEFT JOIN Logs l ON v.Id = l.VoucherId AND l.EventType = @eventtype " +
                        "WHERE v.BatchId = @batchid AND l.id IS NULL",
                    new SQLiteParameter("@eventtype", VendorEvent.VendorEventType.PrintVoucher),
                    new SQLiteParameter("@batchid", BatchID)));
                LastVoucherSequenceNumber = FirstVoucherSequenceNumber + (int)NumVouchers - 1;
            }
            else {
                MessageBox.Show("An unknown error has occured. Please try again.", "Voucher numbering error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                this.Close();
                return;
            }
            BatchForm BatchForm = (BatchForm)Application.OpenForms["BatchForm"];
            grpAlignment.Hide();
            this.Height = 553;
            lblBusyPrinting.Show();
            this.Enabled = false;
            Thread t = new Thread(() =>
            {
                var db = Globals.DB;
                //using (var db = Utility.OpenDBConnection())
                {
                    Utility.PrintVouchers(db, BatchID, FirstVoucherSequenceNumber, LastVoucherSequenceNumber);
                    Globals.OpenBatches.Remove(BatchID);
                    this.Invoke((Action)(() =>
                    {
                        BatchForm.PopulateGrid();
                        this.Enabled = true;
                        this.Close();
                    }));
                }
            });
            t.Start();

        }

        private void grpAlignment_Enter(object sender, EventArgs e)
        {

        }

        private void tmrPrinterKeepalive_Tick(object sender, EventArgs e)
        {
            BatchForm BatchForm = (BatchForm)Application.OpenForms["BatchForm"];
            BatchForm.ResetTimer();
        }

        private void PrintAlignmentDialog_FormClosed(object sender, FormClosedEventArgs e)
        {
            Globals.OpenBatches.Remove(BatchID);
        }

        private void btnExpand_Click(object sender, EventArgs e)
        {
            expanded = !expanded;
            if (expanded) {
                Height = maxHeight;
                btnExpand.Image = Properties.Resources.whiteup;
            }
            else {
                Height = minHeight;
                btnExpand.Image = Properties.Resources.whitedown;
            }
        }

        private void settingsButton_Click(object sender, EventArgs e)
        {
            var dialog = new PrinterSettingsForm();
            dialog.InitString = Utility.GetSavedParameter(Globals.DB, "PrinterInitString");
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                Utility.UpdateSavedParameter(Globals.DB, "PrinterInitString", dialog.InitString);
            }
        }
    }
}
