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

        private lib.BtScanLib btScanLib;

        private List<lib.db.HT_IB_RC> inboundItems;
        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_InboundRecheckDetail(List<lib.db.HT_IB_RC> inboundItems, int selectedIndex)
        {
            InitializeComponent();

            this.inboundItems = inboundItems;
            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, inboundItems.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_InboundRecheck._Form_Instance.Show();
            this.Close();
        }

        private void form_Reset()
        {
            lib.db.HT_IB_RC ib = inboundItems.ElementAt(currentItem); 
            
            lib.db.Item item;
            __ItemList.TryGetValue(ib.__COLUMNS["item_id"], out item);
            
            txtProductDate.Text = ib.__COLUMNS["product_date"];
            txtProductCode.Text = ib.__COLUMNS["item_id"];
            txtLocationFix.Text = item.__COLUMNS["location_fix"];
            txtLocationLast.Text = item.__COLUMNS["location_last"];
            txtLocation.Text = ib.__COLUMNS["location_id"];
            lblLocationDiv.Text = ib.__COLUMNS["location_dvsn_id"];
            txtBoxQty.Text = ib.__COLUMNS["pkg_qty_act"];
            txtPsQty.Text = ib.__COLUMNS["pc_qty_act"];

            btnConfirm.Enabled = false;
            if (ib.__COLUMNS["status"].Equals(String.Empty))
            {
                btnConfirm.Enabled = true;
            }

            btnPrev.Enabled = false;
            btnNext.Enabled = false;
            if (currentItem < inboundItems.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))
            {
                Form frm = new Form_Msg("Input error", Color.Red);
                frm.ShowDialog();
                return;
            }

            // Add inbound record
            lib.db.HT_IB_RC ib = inboundItems.ElementAt(currentItem);
            Dictionary<string, string> cols = new Dictionary<string, string>(ib.__COLUMNS);

            ib.__COLUMNS["pkg_qty_act"] = txtBoxQty.Text;
            ib.__COLUMNS["pc_qty_act"] = txtPsQty.Text;
            ib.__COLUMNS["location_id"] = txtLocation.Text;
            ib.__COLUMNS["location_dvsn_id"] = lblLocationDiv.Text;
            ib.__COLUMNS["status"] = "Complete";

            ib.__COLUMNS.Remove("id");
            ib.__COLUMNS.Remove("update_date");
            ib.__COLUMNS.Remove("update_time");
            ib.__COLUMNS.Remove("update_by");

            int ret = ib.add(ib.__COLUMNS);

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

                // update item back to buffer list
                inboundItems[currentItem] = ib;
                Form_InboundRecheck.inboundItems = inboundItems;

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

                btnConfirm.Enabled = false;

                isModified = false;
            }
            else
            {
                Form frm = new Form_Msg("Input 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, inboundItems.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, inboundItems.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();
            }
        }


    }
}
