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 Bt.ScanLib;
using Bt;
using CsvReadWrite;
using System.Threading;
using Bt.FileLib;
using Bt.SysLib;
using System.IO;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;


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

        private lib.BtScanLib btScanLib;

        private List<lib.db.HT_OB> outboundItems;
        private int currentItem; // zero base item index
        bool isModified = false;

        // 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.Location> __LocationList = lib.db.Location.getLocationList();

        public Form_OutboundDetail(List<lib.db.HT_OB> outboundItems, int selectedIndex)
        {
            InitializeComponent();

            this.outboundItems = outboundItems;
            this.currentItem = selectedIndex;
        }

        private void Form_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;

            // set display elements
            //txtDate.Text = DateTime.Now.ToString("dd/MM/yyyy");

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

            // Initiate data
            form_Reset();

            lbUser.Text = Form_Login._Form_LoginInstance.userName;
            lblPage.Text = String.Format("{0}/{1}", currentItem + 1, outboundItems.Count);
        }

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

            // check if available
            lib.db.Location location;
            if (!__LocationList.TryGetValue(location_id, out location))
            {
                Form frm = new Form_Msg("Input error", Color.Red);
                frm.ShowDialog();
                return;
            }

            isModified = true;
            txtLocation.Text = location_id;
            lblLocationDiv.Text = location.__COLUMNS["division"];
        }

        private void btnBack_Click(object sender, EventArgs e)
        {
            if (isModified)
            {
                DialogResult ret = MessageBox.Show("Are you sure to exit? The unsave data will be lost."
                    , "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button2);
                if (ret == DialogResult.No)
                    return;
            }

            btScanLib.OnScan -= btScanLib_OnScan;
            btScanLib.Disable();

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

        private void form_Reset()
        {
            lib.db.HT_OB ob = outboundItems.ElementAt(currentItem); 
            
            lib.db.Item item;
            __ItemList.TryGetValue(ob.__COLUMNS["item_id"], out item);
            
            txtProductDate.Text = ob.__COLUMNS["product_date"];
            txtProductCode.Text = ob.__COLUMNS["item_id"];
            txtLocationLast.Text = item.__COLUMNS["location_last"];
            txtLocationPlan.Text = ob.__COLUMNS["location_id"];
            lblLocationDiv.Text = ob.__COLUMNS["location_dvsn_id"];
            txtBoxQtyPlan.Text = ob.__COLUMNS["pkg_qty_plan"];
            txtPsQtyPlan.Text = ob.__COLUMNS["pc_qty_plan"];
            txtBoxQty.Text = ob.__COLUMNS["pkg_qty_act"].Equals("0") ? "" : ob.__COLUMNS["pkg_qty_act"];
            txtPsQty.Text = ob.__COLUMNS["pc_qty_act"].Equals("0") ? "" : ob.__COLUMNS["pc_qty_act"];

            btnConfirm.Enabled = false;
            if (!ob.__COLUMNS["status"].Equals("Complete"))
            {
                btnConfirm.Enabled = true;
            }
            else
            {
                txtLocation.Text = ob.__COLUMNS["location_id"];
            }

            btnPrev.Enabled = false;
            btnNext.Enabled = false;
            if (currentItem < outboundItems.Count - 1)
            {
                btnNext.Enabled = true;
            }
            if (currentItem > 0)
            {
                btnPrev.Enabled = true;
            }
            isModified = false;
        }

        private void btnConfirm_Click(object sender, EventArgs e)
        {

            if (txtLocation.Text.Trim().Equals(String.Empty)
                || !txtLocationPlan.Text.Trim().Equals(txtLocation.Text.Trim())
                || txtBoxQty.Text.Trim().Equals(String.Empty))
            {
                Form frm = new Form_Msg("Input error", Color.Red);
                frm.ShowDialog();
                return;
            }

            bool isDigit = false;
            string pattern = @"^[\d]+$";
            Match match = Regex.Match(txtBoxQty.Text, pattern);
            if (!match.Success || !txtBoxQty.Text.Equals(txtBoxQtyPlan.Text)) {
                Form frm = new Form_Msg("Input error", Color.Red);
                frm.ShowDialog();
                return;
            }

            // Add inbound record
            lib.db.HT_OB ob = outboundItems.ElementAt(currentItem);
            Dictionary<string, string> cols = new Dictionary<string, string>(ob.__COLUMNS);

            ob.__COLUMNS["pkg_qty_act"] = txtBoxQty.Text;
            ob.__COLUMNS["pc_qty_act"] = txtPsQty.Text;
            ob.__COLUMNS["update_date"] = DateTime.Now.ToString("yyyyMMdd");
            ob.__COLUMNS["update_time"] = DateTime.Now.ToString("HHmmss");
            ob.__COLUMNS["update_by"] = Form_Login._Form_LoginInstance.userName;

            long boxQty, boxQtyPlan;
            boxQty = long.Parse(txtBoxQty.Text);
            boxQtyPlan = long.Parse(txtBoxQtyPlan.Text);

            ob.__COLUMNS["status"] = boxQtyPlan == boxQty ? "Complete" : "Working";

            ob.__COLUMNS.Remove("id");
            int ret = ob.set(ob.__COLUMNS, "id=" + cols["id"]);

            logger.Log("ret=" + ret);
            if (ret == Bt.LibDef.BT_OK)
            {
                // update location last
                (new lib.db.Item()).set(
                    new Dictionary<string, string> { { "location_last", txtLocation.Text } },
                    "id='" + ob.__COLUMNS["item_id"] + "'"
                    );

                // update last location
                cols = new Dictionary<string, string>
                {
                    { "location_last" , txtLocation.Text }
                };
                (new lib.db.Item()).set(cols, String.Format("id='{0}' AND division={1}", ob.__COLUMNS["item_id"], ob.__COLUMNS["item_dvsn_id"]));

                // update item back to buffer list
                outboundItems[currentItem] = ob;
                Form_Outbound.outboundItems = outboundItems;

                Form frm = new Form_Msg("Confirmed", Color.Black);
                frm.ShowDialog();

                btnConfirm.Enabled = false;

                isModified = false;
            }
            else
            {
                Form frm = new Form_Msg("Result error", Color.Red);
                frm.ShowDialog();
            }
        }

        private void btnPrev_Click(object sender, EventArgs e)
        {
            if (isModified)
            {
                DialogResult ret = MessageBox.Show("Are you sure to go previous page? The unsave data will be lost."
                    , "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button2);
                if (ret == DialogResult.No)
                    return;
            }

            currentItem--;
            lblPage.Text = String.Format("{0}/{1}", currentItem + 1, outboundItems.Count);
            form_Reset();
        }

        private void btnNext_Click(object sender, EventArgs e)
        {
            if (isModified)
            {
                DialogResult ret = MessageBox.Show("Are you sure to go next page? The unsave data will be lost."
                    , "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button2);
                if (ret == DialogResult.No)
                    return;
            }

            currentItem++;
            lblPage.Text = String.Format("{0}/{1}", currentItem + 1, outboundItems.Count);
            form_Reset();
        }

        private void txtBoxQty_TextChanged(object sender, EventArgs e)
        {
            string pattern = @"^[\d]+$";
            Match m = Regex.Match(txtBoxQty.Text, pattern, RegexOptions.IgnoreCase);
            if (m.Success)
            {
                txtPsQty.Text = (int.Parse(txtBoxQty.Text) * __PackageTypes[txtProductCode.Text]).ToString();
            }
        }


    }
}
