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_OutboundSchedule : Form
    {
        public static Form _Form_Instance;
        private lib.LogWriter logger = lib.LogWriter.getInstance();
        public static List<OutboundItemScheduleDisplay> outboundScheduleItems;

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

        public Form_OutboundSchedule()
        {
            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;

            _Form_Instance = this;

            // set display elements
            dtPickerOutboundDate.Value = DateTime.Now;
            cmbCustomer.DataSource = new BindingSource(__CustomerList, null);
            cmbCustomer.DisplayMember = "Key";
            cmbCustomer.ValueMember = "Key";

            // data grid
            InitialDataGrid();

            // Initiate dataGrid
            queryRecord();
        }

        private void btnMenu_Click(object sender, EventArgs e)
        {
            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<OutboundItemScheduleDisplay>()).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 (outboundScheduleItems.Count() == 0) return;

                int row = dataGrid.CurrentCell.RowNumber;

                Form frm = new Form_Outbound(dtPickerOutboundDate.Value
                    , cmbCustomer.SelectedValue.ToString(), outboundScheduleItems, 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;
        }

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


        /////////////////////////////////////////////////////////////
        /// Query
        /////////////////////////////////////////////////////////////
        private void queryRecord()
        {

            string outboundDate;
            string customerId;

            try
            {
                outboundDate = dtPickerOutboundDate.Value.ToString("yyyyMMdd");
                customerId = cmbCustomer.SelectedValue.ToString();
            }
            catch (Exception)
            {
                return;
            }

            if (outboundDate.Equals(string.Empty) || customerId.Equals(string.Empty))
                return;

            outboundScheduleItems = new List<OutboundItemScheduleDisplay>();

            string sql = @"
                SELECT item_id, sum(pkg_qty_plan) AS box_plan, sum(pc_qty_plan) AS qty_plan, sum(pc_qty_act) AS qty_act 
                FROM HT_OB
                WHERE customer_id='{0}' AND outbound_date='{1}'
                GROUP BY item_id";
            List<string[]> rows = (new lib.DbTable()).executeQuery(
                String.Format(sql, customerId, outboundDate));
            int i = 0;
            foreach (string[] row in rows)
            {
                string status = "";
                int qty_plan = int.Parse(row[2]);
                int qty_act = int.Parse(row[3]);
                if (qty_plan == qty_act && qty_act != 0) {
                    status = "Complete";
                } else if (qty_act > 0) {
                    status = "Working";
                }
                outboundScheduleItems.Add(new OutboundItemScheduleDisplay()
                {
                    No = (++i).ToString(),
                    Item_id = row[0],
                    Pkg_qty = row[1],
                    Qty = int.Parse(row[2]),
                    Status = status
                });
            }

            var blist = new BindingList<OutboundItemScheduleDisplay>(outboundScheduleItems);
            dataGrid.DataSource = blist;
        }

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

    }
}