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 Bt.ScanLib;
using Bt;
using CsvReadWrite;
using System.Data.SqlClient;

namespace HT_SKT_Stock
{
    public partial class FrmChangeLocation : Form
    {
        public static FrmChangeLocation _Form_ChangeLocationInstance;
        public String AppPath = "";
        public List<List<string>> tableList;
        List<DisplayTable> lstTable = new List<DisplayTable>();
        private BtScanLib btScanLib;
        private String sysKanbanCode = "";
        private String sysKanbanPart = "";
        private String sysKanbanSerial = "";
        private String sysRow = "";

        public FrmChangeLocation()
        {
            InitializeComponent();

            // Enable BTScanLib
            btScanLib = BtScanLib.getInstance();
            btScanLib.OnScan += new ScanEventHandler(btScanLib_OnScan);
            btScanLib.Debug = false;
            btScanLib.Enable();

            this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.FrmChangeLocation_KeyDown);

            btnBack.KeyDown += new System.Windows.Forms.KeyEventHandler(this.FrmChangeLocation_KeyDown);

            btnConfirm.KeyDown += new System.Windows.Forms.KeyEventHandler(this.FrmChangeLocation_KeyDown);

            txtNewLocation.KeyDown += new System.Windows.Forms.KeyEventHandler(this.FrmChangeLocation_KeyDown);

            dataGrid1.KeyDown += new System.Windows.Forms.KeyEventHandler(this.FrmChangeLocation_KeyDown);

        }

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

            this.MaximizeBox = !this.MaximizeBox;
            this.MinimizeBox = !this.MinimizeBox;

            _Form_ChangeLocationInstance = this;


            String path = this.GetType().Assembly.GetModules()[0].FullyQualifiedName;
            Int32 en = path.LastIndexOf("\\");
            AppPath = path.Substring(0, en);

            lblUser.Text = "User : " + FrmLogin._Form_LoginInstance.userName;

        }

        private Int32 CheckLocationScan(string location)
        {
            try
            {


                tableList = new List<List<string>>();

                SqlConnection objConn = new SqlConnection();
                SqlCommand objCmd = new SqlCommand();
                SqlDataAdapter dtAdapter = new SqlDataAdapter();

                DataSet ds = new DataSet();
                DataTable dt;
                String strSQL;

                Int32 qtyScan = 0;


                strSQL = "EXEC sp_get_location @location = '" + location
                    + "'";

                objConn.ConnectionString = FrmLogin.strConnString;
                objConn.Open();
                objCmd.Connection = objConn;
                objCmd.CommandText = strSQL;
                objCmd.CommandType = CommandType.Text;


                dtAdapter.SelectCommand = objCmd;

                dtAdapter.Fill(ds);
                dt = ds.Tables[0];

                if (dt.Rows.Count > 0)
                {
                    return 1;
                }
                else
                {
                    return 2;
                }


                dtAdapter = null;
                objConn.Close();
                objConn = null;

            }
            catch (Exception)
            {
                return 3;

            }


        }

        private void InitialDataGrid()
        {
            int grid_width = 445;
            // hidden column and row header
            dataGrid1.ColumnHeadersVisible = true;
            dataGrid1.RowHeadersVisible = false;

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

            // Column 0
            DataGridTextBoxColumn tbc0 = new DataGridTextBoxColumn();
            tbc0.Width = 25;
            tbc0.MappingName = "DRow";
            tbc0.HeaderText = "#";
            tableStyle.GridColumnStyles.Add(tbc0);

            // Column 1
            DataGridTextBoxColumn tbc1 = new DataGridTextBoxColumn();
            tbc1.Width = 70;
            tbc1.MappingName = "Partno";
            tbc1.HeaderText = "Part no";
            tableStyle.GridColumnStyles.Add(tbc1);

            // Column 2
            DataGridTextBoxColumn tbc2 = new DataGridTextBoxColumn();
            tbc2.Width = 60;
            tbc2.MappingName = "serialNo";
            tbc2.HeaderText = "Serial";
            tableStyle.GridColumnStyles.Add(tbc2);

            // Column 3
            DataGridTextBoxColumn tbc3 = new DataGridTextBoxColumn();
            tbc3.Width = 45;
            tbc3.MappingName = "qtySerial";
            tbc3.HeaderText = "Qty";
            tableStyle.GridColumnStyles.Add(tbc3);


            dataGrid1.TableStyles.Clear();
            dataGrid1.TableStyles.Add(tableStyle);


        }

        
        private String CheckStockScan(string PartNo, string serial)
        {
            try
            {


                tableList = new List<List<string>>();

                SqlConnection objConn = new SqlConnection();
                SqlCommand objCmd = new SqlCommand();
                SqlDataAdapter dtAdapter = new SqlDataAdapter();

                DataSet ds = new DataSet();
                DataTable dt;
                String strSQL;

                Decimal qtyScan = 0;


                strSQL = "EXEC sp_get_Stock_Change_table @partNo = '" + PartNo
                    + "' , @serial = '" + serial + "'";

                objConn.ConnectionString = FrmLogin.strConnString;
                objConn.Open();
                objCmd.Connection = objConn;
                objCmd.CommandText = strSQL;
                objCmd.CommandType = CommandType.Text;


                dtAdapter.SelectCommand = objCmd;

                dtAdapter.Fill(ds);
                dt = ds.Tables[0];

                if (dt.Rows.Count > 0)
                {
                    string strQty = dt.Rows[0]["qty"].ToString();
                    //strQty = strQty.Substring(0, strQty.Length - 3);
                    return "1" + strQty;
                }
                else
                {
                    return "2";
                }


                dtAdapter = null;
                objConn.Close();
                objConn = null;

            }
            catch (Exception)
            {
                return "3";

            }


        }


        void btScanLib_OnScan(string result)
        {

            if (txtNewLocation.Text == "")
            {
                string location = result;
                Int32 intCheck = CheckLocationScan(location);

                if (intCheck == 1)
                {
                    txtNewLocation.Text = result;
                    return;
                }
                else if (intCheck == 2)
                {
                    WarningErr1 err = new WarningErr1("Scan Location Incorrect");
                    err.ShowDialog();
                }
                else if (intCheck == 3)
                {
                    WarningErr1 err = new WarningErr1("Error Database Connection");
                    err.ShowDialog();
                }

            }
            else
            {

                string[] kanban = result.Split('|');
                string kanbanCode = "";
                string kanbanClass = "";
                string remainderClass = "";
                string partNoScan = "";
                string quantity = "0";
                string kanbanSerialNo = "";
                Int32 intCheck1 = 0;
                string strStatus = "";
                bool blCheckDuplicate = false;
                string quantityAll = "0";
                string qtyStock = "0";

                if (kanban.Length == 6)
                {
                    kanbanCode = kanban[0];
                    kanbanClass = kanban[1];
                    remainderClass = kanban[2];
                    partNoScan = kanban[3];
                    quantity = kanban[4];
                    kanbanSerialNo = kanban[5];


                    if (remainderClass == "2")
                    {
                        quantity = "";
                    }
                    FrmLogin.strQty = quantity;

                    //******* disable BTScanLib
                    btScanLib.OnScan -= btScanLib_OnScan;
                    btScanLib.Disable();

                    FrmInputQty input = new FrmInputQty(quantity);
                    input.ShowDialog();

                    // Enable BTScanLib
                    btScanLib = BtScanLib.getInstance();
                    btScanLib.OnScan += new ScanEventHandler(btScanLib_OnScan);
                    btScanLib.Debug = false;
                    btScanLib.Enable();

                    quantity = FrmLogin.strQty;

                    if (quantity == "")
                    {
                        quantity = "0";
                    }

                    try
                    {

                        String strCheck = CheckStockScan(partNoScan, kanbanSerialNo);
                        
                        if (strCheck.Substring(0,1) == "1")
                        {
                            qtyStock = strCheck.Substring(1, strCheck.Length - 1);
                            
                        }
                        else if (strCheck.Substring(0, 1) == "2")
                        {
                            WarningErr1 err = new WarningErr1("Scan Kanban Incorrect");
                            err.ShowDialog();
                            return;
                        }
                        else if (strCheck.Substring(0, 1) == "3")
                        {
                            WarningErr1 err = new WarningErr1("Error Database Connection");
                            err.ShowDialog();
                            return;
                        }

                        if (lstTable.Count == 0)
                        {
                            //strStatus = "OK";
                            sysKanbanCode = kanbanCode;
                            sysKanbanPart = partNoScan;
                            sysKanbanSerial = kanbanSerialNo;
                            sysRow = "1";



                            lblQtyAll.Text = qtyStock;

                            lstTable.Add(new DisplayTable
                            {
                                Partno = partNoScan,
                                DRow = sysRow,
                                serialNo = kanbanSerialNo,
                                qtySerial = qtyStock,
                                //statusSerial = strStatus
                            });

                            var blist = new BindingList<DisplayTable>(lstTable);
                            dataGrid1.DataSource = blist;

                            InitialDataGrid();

                            dataGrid1.Focus();
                        }
                        else
                        {
                            quantityAll = "0";
                            foreach (var item in lstTable)
                            {

                                if (item.serialNo == kanbanSerialNo)
                                {
                                    blCheckDuplicate = true;

                                }

                                quantityAll = (Convert.ToDecimal(quantityAll) + Convert.ToDecimal(item.qtySerial)).ToString();



                                //if (item.statusSerial == "OK")
                                //{


                                //}

                            }


                            if (blCheckDuplicate == true)
                            {
                                //sysRow = (Convert.ToInt32(sysRow) + 1).ToString();
                                //strStatus = "NG";
                                //lstTable.Add(new DisplayTable
                                //{
                                //    Partno = partNoScan,
                                //    DRow = sysRow,
                                //    serialNo = kanbanSerialNo,
                                //    qtySerial = quantity,
                                //    statusSerial = strStatus
                                //});

                                //var blist = new BindingList<DisplayTable>(lstTable);
                                //dataGrid1.DataSource = blist;

                                //InitialDataGrid();

                                ////******* disable BTScanLib
                                //btScanLib.OnScan -= btScanLib_OnScan;
                                //btScanLib.Disable();

                                //FrmWarningLeader err = new FrmWarningLeader("Duplicate scans of the", "same serial", "");
                                //err.ShowDialog();

                                //// Enable BTScanLib
                                //btScanLib = BtScanLib.getInstance();
                                //btScanLib.OnScan += new ScanEventHandler(btScanLib_OnScan);
                                //btScanLib.Debug = false;
                                //btScanLib.Enable();

                                //if (lstTable.Count > 0)
                                //{
                                //    dataGrid1.CurrentRowIndex = lstTable.Count - 1;
                                //}

                                //dataGrid1.Focus();

                                return;
                            }
                            //else if (partNoScan != sysKanbanPart)
                            //{
                            //    sysRow = (Convert.ToInt32(sysRow) + 1).ToString();
                            //    strStatus = "NG";
                            //    lstTable.Add(new DisplayTable
                            //    {
                            //        Partno = partNoScan,
                            //        DRow = sysRow,
                            //        serialNo = kanbanSerialNo,
                            //        qtySerial = quantity,
                            //        statusSerial = strStatus
                            //    });

                            //    var blist = new BindingList<DisplayTable>(lstTable);
                            //    dataGrid1.DataSource = blist;

                            //    InitialDataGrid();

                            //    //******* disable BTScanLib
                            //    btScanLib.OnScan -= btScanLib_OnScan;
                            //    btScanLib.Disable();

                            //    FrmWarningLeader err = new FrmWarningLeader("", "", "Different part no.");
                            //    err.ShowDialog();

                            //    // Enable BTScanLib
                            //    btScanLib = BtScanLib.getInstance();
                            //    btScanLib.OnScan += new ScanEventHandler(btScanLib_OnScan);
                            //    btScanLib.Debug = false;
                            //    btScanLib.Enable();

                            //    if (lstTable.Count > 0)
                            //    {
                            //        dataGrid1.CurrentRowIndex = lstTable.Count - 1;
                            //    }

                            //    dataGrid1.Focus();

                            //    return;
                            //}
                            //else if (kanbanCode != sysKanbanCode)
                            else if (kanbanCode != "1")
                            {
                                //sysRow = (Convert.ToInt32(sysRow) + 1).ToString();
                                //strStatus = "NG";
                                //lstTable.Add(new DisplayTable
                                //{
                                //    Partno = partNoScan,
                                //    DRow = sysRow,
                                //    serialNo = kanbanSerialNo,
                                //    qtySerial = quantity,
                                //    statusSerial = strStatus
                                //});

                                //var blist = new BindingList<DisplayTable>(lstTable);
                                //dataGrid1.DataSource = blist;

                                //InitialDataGrid();

                                ////******* disable BTScanLib
                                //btScanLib.OnScan -= btScanLib_OnScan;
                                //btScanLib.Disable();

                                //FrmWarningLeader err = new FrmWarningLeader("", "", "Different types of Kanban");
                                //err.ShowDialog();

                                //// Enable BTScanLib
                                //btScanLib = BtScanLib.getInstance();
                                //btScanLib.OnScan += new ScanEventHandler(btScanLib_OnScan);
                                //btScanLib.Debug = false;
                                //btScanLib.Enable();

                                //if (lstTable.Count > 0)
                                //{
                                //    dataGrid1.CurrentRowIndex = lstTable.Count - 1;
                                //}

                                //dataGrid1.Focus();

                                return;
                            }
                            else
                            {
                                sysRow = (Convert.ToInt32(sysRow) + 1).ToString();
                                //strStatus = "OK";
                                quantityAll = (Convert.ToDecimal(quantityAll) + Convert.ToDecimal(qtyStock)).ToString();
                                lblQtyAll.Text = quantityAll;
                                lstTable.Add(new DisplayTable
                                {
                                    Partno = partNoScan,
                                    DRow = sysRow,
                                    serialNo = kanbanSerialNo,
                                    qtySerial = qtyStock,
                                    //statusSerial = strStatus
                                });

                                var blist = new BindingList<DisplayTable>(lstTable);
                                dataGrid1.DataSource = blist;

                                InitialDataGrid();

                                if (lstTable.Count > 0)
                                {
                                    dataGrid1.CurrentRowIndex = lstTable.Count - 1;
                                }

                                dataGrid1.Focus();
                            }
                        }



                    }
                    catch (Exception)
                    {

                    }

                }
                else
                {
                    WarningErr1 err = new WarningErr1("Kanban Format Incorrect");
                    err.ShowDialog();

                    if (lstTable.Count > 0)
                    {
                        dataGrid1.CurrentRowIndex = lstTable.Count - 1;
                    }

                    dataGrid1.Focus();
                }

            }

        }

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

            FrmStockMenu._Form_StockMenuInstance.Show();
            //Bt.ScanLib.Control.btScanDisable();
            //this.Hide();
            this.Close();
        }

        private void FrmChangeLocation_KeyDown(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode.ToString())
            {

                case "F1":
                    btnBack_Click(sender, e);
                    break;

                case "F4":
                    btnConfirm_Click(sender, e);
                    break;
            }
        }

        private void btnConfirm_Click(object sender, EventArgs e)
        {
            if (lstTable.Count == 0)
            {
                WarningErr1 errEmptyData = new WarningErr1("Empty Data ");
                errEmptyData.ShowDialog();

                dataGrid1.Focus();

                return;
            }

            foreach (var item in lstTable)
            {

                
                UpdateStockTracking(item.Partno, txtNewLocation.Text, item.serialNo, item.qtySerial);

            }

            WarningErr2 err = new WarningErr2("Data registration", "completed", "Green");
            err.ShowDialog();

            //******* disable BTScanLib
            btScanLib.OnScan -= btScanLib_OnScan;
            btScanLib.Disable();

            FrmStockMenu._Form_StockMenuInstance.Show();
            //Bt.ScanLib.Control.btScanDisable();
            //this.Hide();
            this.Close();
        }

        private void UpdateStockTracking(string partNo, string locationId, string serial, string quantity)
        {
            try
            {


                SqlConnection objConn = new SqlConnection();
                SqlCommand objCmd = new SqlCommand();
                SqlDataAdapter dtAdapter = new SqlDataAdapter();

                DataSet ds = new DataSet();
                DataTable dt;
                String strSQL;

                Decimal qtyScan = Convert.ToDecimal(quantity);


                strSQL = "EXEC sp_update_change_stock @partNo = '" + partNo
                    + "' , @locationId = '" + locationId + "' , @serial = '" + serial
                    + "' , @qtySerial = " + quantity + " , @userId = '" + FrmLogin._Form_LoginInstance.userName
                    + "'";

                objConn.ConnectionString = FrmLogin.strConnString;
                objConn.Open();
                objCmd.Connection = objConn;
                objCmd.CommandText = strSQL;
                objCmd.CommandType = CommandType.Text;


                objCmd.ExecuteNonQuery();

                objConn.Close();
                objConn = null;

            }
            catch (Exception)
            {

            }

        }

    }
}