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

        public static Form_StockCheck _Form_Instance;
        List<StockManagementItemDisplay> items;

        // 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_StockCheck()
        {
            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
            lblProductName.Text = "";

            // data grid
            items = new List<StockManagementItemDisplay>(); // clear Data List
            InitialDataGrid();
        }

        void btScanLib_OnScan(string result)
        {
            string item_id = result;

            if (!__ItemList.Keys.Contains(item_id))
            {
                Form frm = new Form_Msg(String.Format("Item[{0}] not found", item_id), Color.Red);
                frm.ShowDialog();
                return;
            }

            txtProductCode.Text = item_id;
            lblProductName.Text = __ItemList[item_id].__COLUMNS["name"];

            // inquiry item from stock master
            queryRecord();
        }

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

            Form_StockManagementMenu._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<StockManagementItemDisplay>()).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 * 30 / 100;
            tbc2.MappingName = "Location_id";
            tbc2.HeaderText = "Location";
            tableStyle.GridColumnStyles.Add(tbc2);

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

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

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

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

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

                int row = dataGrid.CurrentCell.RowNumber;
                
                if (items.ElementAt(row).No.Equals(String.Empty)) return;

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

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


        /////////////////////////////////////////////////////////////
        /// Query
        /////////////////////////////////////////////////////////////
        private void queryRecord()
        {
            string item_id = txtProductCode.Text;
            if (item_id.Trim().Equals(String.Empty))
                return;

            double t_pkg_qty = 0;
            double t_qty = 0;

            items = new List<StockManagementItemDisplay>();

            List<string[]> rows = (new lib.db.Stock()).get(
                (new lib.db.Stock()).__COLUMNS
                , "item_id='" + item_id + "'"
                , null, null, null);
            int i = 0;
            foreach (string[] row in rows)
            {
                logger.Log(row);
                items.Add(new StockManagementItemDisplay()
                {
                    No = (++i).ToString(),
                    Item_id = item_id,
                    Item_name = __ItemList[item_id].__COLUMNS["name"],
                    Location_id = row[2],
                    Product_date = row[4],
                    Pkg_qty = String.Format("{0:0.##}", double.Parse(row[5]) / __PackageTypes[item_id]),
                    Qty = row[5]
                });
            }

            // Add total row
            foreach (StockManagementItemDisplay item in items)
            {
                t_pkg_qty += double.Parse(item.Pkg_qty);
                t_qty += double.Parse(item.Qty);
            }
            items.Add(new StockManagementItemDisplay());
            items.Add(new StockManagementItemDisplay());
            items.Add(new StockManagementItemDisplay()
            {
                Location_id = "Total",
                Pkg_qty = String.Format("{0:0.##}", t_pkg_qty),
                Qty = String.Format("{0:0.##}", t_qty)
            });

            var blist = new BindingList<StockManagementItemDisplay>(items);
            dataGrid.DataSource = blist;
        }

        private void Form_StockCheck_Activated(object sender, EventArgs e)
        {

            // Enable BTScanLib
            if (!scanHandler)
            {
                btScanLib = lib.BtScanLib.getInstance();
                btScanLib.OnScan += new SCAN.lib.ScanEventHandler(btScanLib_OnScan);
                scanHandler = false;
                btScanLib.Debug = false;
                btScanLib.Enable();
            }
        }

    }
}