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_InboundRepack : Form
    {
        private lib.LogWriter logger = lib.LogWriter.getInstance();

        public static Form_InboundRepack _Form_Instance;
        public static List<lib.db.HT_IB_RP> inboundItems;

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

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

        public Form_InboundRepack()
        {
            InitializeComponent();

            lbUser.Text = Form_Login._Form_LoginInstance.userName;

        }

        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;

            // set display elements
            lblInboundDate.Text = DateTime.Now.ToString("dd/MM/yyyy tt").Replace('-', '/');

            // data grid
            inboundItems = new List<lib.db.HT_IB_RP>(); // clear Data List
            InitialDataGrid();

            dtPickerProduct.Value = DateTime.Now;

            // Initiate dataGrid
            datePicker_ValueChanged(sender, e);
        }

        void btScanLib_OnScan(string result)
        {
            string item_id = result;
            int packing_size = __PackageTypes[item_id];
            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_IB_RP().__COLUMNS);

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

            cols["item_id"] = item_id;
            cols["item_dvsn_id"] = item_div;
            cols["create_date"] = DateTime.Now.ToString("yyyyMMdd");
            cols["create_time"] = DateTime.Now.ToString("HHmmss");
            cols["create_by"] = Form_Login._Form_LoginInstance.userName;
            cols["product_date"] = dtPickerProduct.Value.ToString("yyyyMMdd");
            cols["pkg_qty_act"] = "1";
            cols["pkg_type_act"] = "box";
            cols["pc_qty_act"] = packing_size.ToString();

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


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

            List<InboundItemDisplay> items = InboundItemDisplay.LoadCollectionData(inboundItems);

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

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

            Form_InboundMenu._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<InboundItemDisplay>()).GetType().Name;

            // Column 1
            DataGridTextBoxColumn tbc1 = new DataGridTextBoxColumn();
            tbc1.Width = grid_width * 10 / 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 = "Parts no";
            tableStyle.GridColumnStyles.Add(tbc2);

            // Column 3
            DataGridTextBoxColumn tbc3 = new DataGridTextBoxColumn();
            tbc3.Width = grid_width * 10 / 100;
            tbc3.MappingName = "Pkg_qty";
            tbc3.HeaderText = "Box";
            tableStyle.GridColumnStyles.Add(tbc3);

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

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

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

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

                int row = dataGrid.CurrentCell.RowNumber;

                // disable scan
                btScanLib.OnScan -= this.btScanLib_OnScan;
                scanHandler = false;
                btScanLib.Disable();

                Form frm = new Form_InboundRepackDetail(inboundItems, row);
                frm.Show();
                this.Hide();
            }
            catch (ArgumentOutOfRangeException ex)
            {
            }
        }

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

        private void datePicker_KeyDown(object sender, KeyEventArgs e)
        {
            e.Handled = true;
        }


        /////////////////////////////////////////////////////////////
        /// Query
        /////////////////////////////////////////////////////////////
        private void queryRecord()
        {
            string inboundDate = DateTime.Now.ToString("yyyyMMdd");
            string productDate = dtPickerProduct.Value.ToString("yyyyMMdd");

            if (inboundDate.Equals(string.Empty) || productDate.Equals(string.Empty))
                return;

            inboundItems = new List<lib.db.HT_IB_RP>();
            
            List<string[]> rows = (new lib.db.HT_IB_RP()).get(
                (new lib.db.HT_IB_RP()).__COLUMNS
                , String.Format("create_date='{0}' AND product_date='{1}'"
                    , inboundDate, productDate)
                , null, null, null);
            foreach (string[] row in rows)
            {
                logger.Log(row);
                inboundItems.Add(new lib.db.HT_IB_RP(row));
            }

            List<InboundItemDisplay> items = InboundItemDisplay.LoadCollectionData(inboundItems);

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

        private void Form_InboundRepack_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<InboundItemDisplay> items = InboundItemDisplay.LoadCollectionData(inboundItems);

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

    }
}