using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Globalization;
using System.Windows;

namespace SCAN
{
    public partial class Form_OutboundSimple : Form
    {
        private lib.LogWriter logger = lib.LogWriter.getInstance();

        public static Form_OutboundSimple _Form_Instance;
        public static List<lib.db.HT_OB> outboundItems;
       // List<OutboundSimpleItemDisplay> items;


        // Master table
        private Dictionary<string, int> __PackageTypes = lib.db.PackageType.getBoxSizeList();
        private Dictionary<string, lib.db.Item> __ItemList = lib.db.Item.getItemList();
        private Dictionary<string, lib.db.Customer> __CustomerList = lib.db.Customer.getCustomerList();

        private string act_type;
        private int datagridIndex;

        private lib.BtScanLib btScanLib;
        private bool scanHandler = false;

        public Form_OutboundSimple(string type)
        {
            InitializeComponent();
            this.act_type = type;
            this.datagridIndex = 0;
            lbUser.Text = Form_Login._Form_LoginInstance.userName;
            if (act_type == "OB")
            {
                lblTitle.Text = "Simple Outbound";
            }

            if (act_type == "OB_RP")
            {
                lblTitle.Text = "Repack Outbound";
            }

            if (act_type == "OB_RC")
            {
                lblTitle.Text = "Recheck Outbound";
            }

            List<string[]> rows = (new lib.db.Customer()).getAll();

            foreach (string[] row in rows)
            {
                list_cust.Items.Add(row[0]);
            }

            list_cust.Text = "ALL";
        }

        private void Form_Load(object sender, EventArgs e)
        {
            // set screen resolution
            if (System.Windows.Forms.Screen.PrimaryScreen.Bounds.Width == 240)
            {
                resolution.ScreenSize.VGAtoQVGA(this);
            }

            // disable maximize and minimize button
            this.MaximizeBox = !this.MaximizeBox;
            this.MinimizeBox = !this.MinimizeBox;

            // set form instance
            _Form_Instance = this;

           
            // data grid
            outboundItems = new List<lib.db.HT_OB>(); 
            InitialDataGrid();
            //queryRecord();

            dtPickerOutbound.Value = DateTime.Now;

            dtPickerOutbound_ValueChanged(sender, e);
            
        }

       
        void btScanLib_OnScan(string result)
        {
            /*
            string[] result_split = result.Split('|');
            string item_id = result_split[0];
            string customer_id = result_split[1];
            */

            string item_id = result;
            if (item_id.Length == 0 )
            {
                logger.Log(String.Format("Scan Barcode Outbound Simple Error! : item_id={0}", item_id));
            }
            else
            {

                lib.db.Item item;
                __ItemList.TryGetValue(item_id, out item);
                logger.Log(item.__COLUMNS.Values.ToArray<string>());

                string customer_id;
                item.__COLUMNS.TryGetValue("customer_id", out customer_id);
                logger.Log("customer_id=" + customer_id);


                string current_cust = list_cust.Text;
                if (current_cust != "ALL" && current_cust != customer_id)
                {
                    Form frmMsg = new Form_Msg("Barcode Customer Not Match \"" + current_cust + "\"", Color.Blue);
                    frmMsg.ShowDialog();
                    frmMsg.Dispose();
                    return;
                }


                if (customer_id.Length > 0 && customer_id != null)
                {
                    float pack_qty_act_before = 0;
                    int pc_qty_act_before = 0;
                    int index_key = -1;
                    string status = "";
                    int rowNumber = 1;

                    if (outboundItems.Count > 0)
                    {
                        for (int i = 0; i < outboundItems.Count; i++)
                        {
                            if (outboundItems.ElementAt(i).__COLUMNS["item_id"] == item_id && outboundItems.ElementAt(i).__COLUMNS["customer_id"] == customer_id && outboundItems.ElementAt(i).__COLUMNS["status"] != "OK")
                            {
                                status = outboundItems.ElementAt(i).__COLUMNS["status"];
                                if (status == "")
                                {
                                    index_key = i;
                                    pack_qty_act_before = float.Parse(outboundItems.ElementAt(i).__COLUMNS["pkg_qty_act"]);
                                    pc_qty_act_before = int.Parse(outboundItems.ElementAt(i).__COLUMNS["pc_qty_act"]);
                                    logger.Log(String.Format("index_key : {0} , pack_qty_act_before : {1}", index_key.ToString(), pack_qty_act_before.ToString(), outboundItems.ElementAt(i).__COLUMNS["act_type"].ToString()));
                                    if (index_key >= 0)
                                    {
                                        outboundItems.RemoveAt(index_key);
                                    }
                                }
                                rowNumber = i + 1;
                            }
                        }
                    }

                    if (status == "")
                    {
                        string item_div;
                        item.__COLUMNS.TryGetValue("division", out item_div);
                        logger.Log("item_div=" + item_div);

                        string customer_dvsn_id;
                        item.__COLUMNS.TryGetValue("customer_dvsn_id", out customer_dvsn_id);
                        logger.Log("customer_dvsn_id=" + customer_dvsn_id);

                        int packing_size = __PackageTypes[item_id];

                        float pkg_qty_act_now = pack_qty_act_before + 1;
                        int pc_qty_act_now = pc_qty_act_before + packing_size;

                        logger.Log(String.Format("item_id={0}, packing_size={1}", item_id, packing_size));

                        Dictionary<string, string> cols = new Dictionary<string, string>(new lib.db.HT_OB().__COLUMNS);

                        cols["item_id"] = item_id;
                        cols["item_dvsn_id"] = item_div;
                        cols["customer_id"] = customer_id;
                        cols["customer_dvsn_id"] = customer_dvsn_id;
                        cols["outbound_date"] = dtPickerOutbound.Value.ToString("yyyyMMdd");
                        cols["product_date"] = "19000101";
                        cols["create_date"] = dtPickerOutbound.Value.ToString("yyyyMMdd");
                        cols["create_time"] = DateTime.Now.ToString("HHmmss");
                        cols["create_by"] = Form_Login._Form_LoginInstance.userName;
                        cols["pkg_qty_act"] = pkg_qty_act_now.ToString();
                        cols["pkg_type_act"] = "box";
                        cols["pc_qty_act"] = pc_qty_act_now.ToString();
                        cols["act_type"] = act_type;

                        logger.Log(cols.Values.ToArray<string>());

                        outboundItems.Add(new lib.db.HT_OB(cols.Values.ToArray<string>()));
                        logger.Log(String.Format("Add item {0} to inboundList size[{1}]", item_id, outboundItems.Count));


                        List<OutboundSimpleItemDisplay> items = OutboundSimpleItemDisplay.LoadCollectionData(outboundItems);

                        dataGrid.DataSource = null;
                        dataGrid.DataBindings.Clear();
                        dataGrid.Refresh();
                        var blist = new BindingList<OutboundSimpleItemDisplay>(items);
                        dataGrid.DataSource = blist;
                        dataGrid.CurrentRowIndex = outboundItems.Count() - 1;
                    }

                    if (status == "Confirm")
                    {
                        Form frmMsg = new Form_Msg("Barcode is status \"Confirm\" at row No." + rowNumber.ToString(), Color.Blue);
                        frmMsg.ShowDialog();
                        frmMsg.Dispose();
                    }
                }
                else 
                {
                    logger.Log("Barcode " + item_id + "not Found Customer ");
                    Form frmMsg = new Form_Msg("barcode \"" + item_id + "\" not Owner.", Color.Red);
                    frmMsg.ShowDialog();
                    frmMsg.Dispose();
                }

            }
           
        }
        

        private void btnBack_Click(object sender, EventArgs e)
        {
            // disable BTScanLib
            btScanLib.OnScan -= btScanLib_OnScan;
            scanHandler = false;
            btScanLib.Disable();

            Form_OutboundMenu._Form_Instance.Show();
            this.Close();
        }


        private void InitialDataGrid()
        {
            int grid_width = 475;
            // hidden column and row header
            dataGrid.ColumnHeadersVisible = true;
            dataGrid.RowHeadersVisible = false;
            dataGrid.Click += new EventHandler(dataGrid_Click);

            // set style
            DataGridTableStyle tableStyle = new DataGridTableStyle();
            tableStyle.MappingName = (new BindingList<OutboundSimpleItemDisplay>()).GetType().Name;

            // Column 1
            DataGridTextBoxColumn tbc1 = new DataGridTextBoxColumn();
            tbc1.Width = grid_width * 6 / 100;
            tbc1.MappingName = "No";
            tbc1.HeaderText = "#";
            tableStyle.GridColumnStyles.Add(tbc1);


            // Column 2
            DataGridTextBoxColumn tbc2 = new DataGridTextBoxColumn();
            tbc2.Width = grid_width * 40 / 100;
            tbc2.MappingName = "Item_id";
            tbc2.HeaderText = "Item";
            tableStyle.GridColumnStyles.Add(tbc2);

            // Column 3
            //DataGridTextBoxColumn tbc3 = new DataGridTextBoxColumn();
            //tbc3.Width = grid_width * 20 / 100;
            //tbc3.MappingName = "Product_date";
            //tbc3.HeaderText = "Lot";
            //tableStyle.GridColumnStyles.Add(tbc3);

            // Column 3
            DataGridTextBoxColumn tbc3 = new DataGridTextBoxColumn();
            tbc3.Width = grid_width * 15 / 100;
            tbc3.MappingName = "Customer_id";
            tbc3.HeaderText = "Cust";
            tableStyle.GridColumnStyles.Add(tbc3);

            // Column 4
            DataGridTextBoxColumn tbc4 = new DataGridTextBoxColumn();
            tbc4.Width = grid_width * 10 / 100;
            tbc4.MappingName = "Pkg_qty_act";
            tbc4.HeaderText = "Box";
            tableStyle.GridColumnStyles.Add(tbc4);


            // Column 5
            DataGridTextBoxColumn tbc5 = new DataGridTextBoxColumn();
            tbc5.Width = grid_width * 15 / 100;
            tbc5.MappingName = "Qty_act";
            tbc5.HeaderText = "Qty";
            tableStyle.GridColumnStyles.Add(tbc5);
            

            // Column 6
            DataGridTextBoxColumn tbc6 = new DataGridTextBoxColumn();
            tbc6.Width = (grid_width * 25 / 100) - 30;
            tbc6.MappingName = "Status";
            tbc6.HeaderText = "Status";
            tableStyle.GridColumnStyles.Add(tbc6);

            dataGrid.TableStyles.Clear();
            dataGrid.TableStyles.Add(tableStyle);
        }

        void dataGrid_Click(object sender, EventArgs e)
        {
            try
            {
                if (outboundItems.Count() == 0) return;

                datagridIndex = dataGrid.CurrentRowIndex;

                if (outboundItems.ElementAt(datagridIndex).__COLUMNS["status"] == "")
                {
                    // disable scan
                    btScanLib.OnScan -= this.btScanLib_OnScan;
                    scanHandler = false;
                    btScanLib.Disable();

                    Form frmOutbSimConfirm = new Form_OutboundSimpleConfirm("", Color.Blue, outboundItems, datagridIndex);
                    frmOutbSimConfirm.ShowDialog();
                    frmOutbSimConfirm.Dispose();
                    return;
                }

                if (outboundItems.ElementAt(datagridIndex).__COLUMNS["status"] == "OK")
                {
                    Form frmMsg = new Form_Msg("Can not edit data send to server Complete.", Color.Blue);
                    frmMsg.ShowDialog();
                    frmMsg.Dispose();
                  
                }

                if (outboundItems.ElementAt(datagridIndex).__COLUMNS["status"] == "Confirm")
                {
                    btScanLib.OnScan -= this.btScanLib_OnScan;
                    scanHandler = false;
                    btScanLib.Disable();

                    Form frmMsgOkCancel = new Form_OutboundMsgOKCancel("Want to edit item No." + (datagridIndex + 1).ToString() + " ?", Color.Blue, outboundItems, datagridIndex);
                    frmMsgOkCancel.ShowDialog();
                    frmMsgOkCancel.Dispose();
               
                }

                dataGrid.CurrentRowIndex = datagridIndex;
            }
            catch (ArgumentOutOfRangeException ex)
            {
                logger.Log(ex.Message);
            }
        }

        /*

        void tbcStatus_OnPaint(Graphics g, Rectangle Bounds, CurrencyManager Source, int RowNum, Brush BackBrush, Brush ForeBrush, bool AlignToRight)
        {

            string value = items[RowNum].Status;

            ForeBrush = new SolidBrush(Color.White);

            if (value.ToLower().Equals("ok"))
            {
                BackBrush = new SolidBrush(Color.LimeGreen);
            }
            else if (value.ToLower().Equals("ng"))
            {
                BackBrush = new SolidBrush(Color.Red);
            }
            else if (value.ToLower().Equals("working"))
            {
                BackBrush = new SolidBrush(Color.Blue);
            }
            else
            {
                BackBrush = new SolidBrush(Color.DarkGray);
            }

            g.FillRectangle(BackBrush, Bounds.X, Bounds.Y, Bounds.Width, Bounds.Height);

            System.Drawing.Font font = new Font(System.Drawing.FontFamily.GenericSansSerif,
                (float)12.25, FontStyle.Regular);
            SizeF size = g.MeasureString(value, font);
            g.DrawString(value, font, ForeBrush,
                Bounds.X + (Bounds.Width - size.Width) / 2, Bounds.Y + ((Bounds.Height - font.Size) / 2));
        }
         * */

        /////////////////////////////////////////////////////////////
        /// Query
        /////////////////////////////////////////////////////////////
        private void queryRecord()
        {
            string customer_id = list_cust.Text;

            string outbound_date = dtPickerOutbound.Value.ToString("yyyyMMdd");
            if (outbound_date.Equals(string.Empty))
                return;

            outboundItems = new List<lib.db.HT_OB>();
            List<string[]> rows;

            if (customer_id == "ALL")
            {
                rows = (new lib.db.HT_OB()).get(
                    (new lib.db.HT_OB()).__COLUMNS
                    , String.Format("outbound_date='{0}' AND act_type='{1}'", outbound_date, act_type)
                    , null, null, null);
            }
            else
            {
                rows = (new lib.db.HT_OB()).get(
                    (new lib.db.HT_OB()).__COLUMNS
                    , String.Format("outbound_date='{0}' AND act_type='{1}' AND customer_id='{2}'", outbound_date, act_type, customer_id)
                    , null, null, null);
            }

            foreach (string[] row in rows)
            {
                logger.Log(row);
                outboundItems.Add(new lib.db.HT_OB(row));
            }

            List<OutboundSimpleItemDisplay> items = OutboundSimpleItemDisplay.LoadCollectionData(outboundItems);

            dataGrid.DataSource = null;
            dataGrid.DataBindings.Clear();
            dataGrid.Refresh();
            var blist = new BindingList<OutboundSimpleItemDisplay>(items);
            dataGrid.DataSource = blist;
        }

        private void Form_OutboundSimple_Activated(object sender, EventArgs e)
        {
            // Enable BTScanLib
            if (!scanHandler)
            {
                btScanLib = lib.BtScanLib.getInstance();
                btScanLib.OnScan += new SCAN.lib.ScanEventHandler(btScanLib_OnScan);
                scanHandler = true;
                btScanLib.Debug = false;
                btScanLib.Enable();
            }

            List<OutboundSimpleItemDisplay> items = OutboundSimpleItemDisplay.LoadCollectionData(outboundItems);

            dataGrid.DataSource = null;
            dataGrid.DataBindings.Clear();
            dataGrid.Refresh();
            var blist = new BindingList<OutboundSimpleItemDisplay>(items);
            dataGrid.DataSource = blist;
            if (outboundItems.Count() > 0)
            {
                if (outboundItems.Count() == datagridIndex) { datagridIndex -= 1; }
                dataGrid.CurrentRowIndex = datagridIndex;
            }

        }

        private void dtPickerOutbound_ValueChanged(object sender, EventArgs e)
        {
            dtPickerOutbound.CustomFormat = "dd/MM/yyyy";
            queryRecord();
        }

        private void Form_OutboundSimple_KeyDown(object sender, KeyEventArgs e)
        {
            if(e.KeyCode.ToString()=="F1")
            {
                btnBack_Click(sender, e);
            }

            if(e.KeyCode.ToString()=="F4")
            {
                btnConfirmAll_Click(sender, e);
            }
        }

        private void btnConfirmAll_Click(object sender, EventArgs e)
        {
            try
            {
                if (outboundItems.Count()==0) return;
                int waitConfirm = 0;
                for (int i = 0; i < outboundItems.Count; i++)
                {
                    if (outboundItems.ElementAt(i).__COLUMNS["status"] == "")
                    {
                        waitConfirm++;
                    }
                }

                if (waitConfirm == 0)
                {
                    btScanLib.OnScan -= this.btScanLib_OnScan;
                    scanHandler = false;
                    btScanLib.Disable();

                    Form frmMsg = new Form_Msg("No item, pending confirmation.", Color.Blue);
                    frmMsg.ShowDialog();
                    frmMsg.Dispose();
                    return;
                }

                if (waitConfirm > 0)
                {
                    btScanLib.OnScan -= this.btScanLib_OnScan;
                    scanHandler = false;
                    btScanLib.Disable();


                    Form frmOutbSimAllConfirm = new Form_OutboundSimpleAllConfirm("", Color.Blue, outboundItems, waitConfirm, act_type);
                    frmOutbSimAllConfirm.ShowDialog();
                    frmOutbSimAllConfirm.Dispose();
                    
                }
            }
            catch (ArgumentOutOfRangeException ex)
            {
                logger.Log(ex.Message);
            }
        }

        private void list_cust_TextChanged(object sender, EventArgs e)
        {
            queryRecord();
        }


    }
}