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.Data.SqlClient;


namespace HT_SKT_Stock
{
    public partial class Loading_PDS : Form
    {
        public static Loading_PDS _FormInstance;		// フォーム
        public String AppPath = "";						// アプリケーション実行パス
        //public String dbFilePath = "\\FlashDisk\\BT_FILES\\drv1\\HT_SKT.DB";
        public String dbFilePath = "\\FlashDisk\\BT_FILES\\drv1\\SKT_Stock\\HT_SKT.DB";
        public int dbIdx = 0;
        public int recordCount = 0;
        private BtScanLib btScanLib;
        
        public Loading_PDS()
        {
            InitializeComponent();

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

        void btScanLib_OnScan(string result)
        {
            try
            {
                listBox1.Items.Add(result.Substring(result.Length - 11, 9));

                btnConfirm.Enabled = true;

            }
            catch (Exception)
            {
                //call error form here
                ErrorForm err = new ErrorForm();
                err.Show();
                
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {

        }

        private void btnConfirm_Click(object sender, EventArgs e)
        {

        }

        private void label1_ParentChanged(object sender, EventArgs e)
        {

        }

        private void label5_ParentChanged(object sender, EventArgs e)
        {

        }

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

            _FormInstance = this;


            // 実行パスを取得
            String path = this.GetType().Assembly.GetModules()[0].FullyQualifiedName;
            Int32 en = path.LastIndexOf("\\");
            AppPath = path.Substring(0, en);
            listBox1.Items.Clear();

            //StringBuilder filenameSet = new StringBuilder("\\FlashDisk\\BT_FILES\\drv1\\SKT\\NoOCR.ini");
            StringBuilder filenameSet = new StringBuilder("\\FlashDisk\\BT_FILES\\drv1\\SKT_Stock\\NoOCR.ini");
            int ret = Setting.btScanLoadOCRConfig(filenameSet);
            SetScanStatus(1, 0, true);
        }

        private void btnConfirm_Click_1(object sender, EventArgs e)
        {
            for (int i = 0; i < listBox1.Items.Count; i++)
            {
                insertRecordPDS(listBox1.Items[i].ToString());
            }
            Form frmD = new Success();
            frmD.ShowDialog();
            frmD.Dispose();
        }

        public void SetScanStatus(int scanMode, int scanStep, bool enn)
        {
            FrmLogin._Form_LoginInstance.ScanStep = scanStep;
            FrmLogin._Form_LoginInstance.ScanMode = scanMode;
            if (enn)
            {
                Bt.ScanLib.Control.btScanEnable();
            }


        }

        public int RcvMsg(string result)
        {
            StringBuilder filenameSet;//= new StringBuilder("\\RamDisk\\KANBAN.ini");
            int ret;//= Setting.btScanLoadOCRConfig(filenameSet);
            int ans = 0;

            switch (FrmLogin._Form_LoginInstance.ScanStep)
            {
               
                case 0://PDS No.
                    listBox1.Items.Add(result.Substring(result.Length-11,9));
                    ans = 1;
                    btnConfirm.Enabled = true;
                    break;
            }
            return ans;

        }

        private void btnCancel_Click_1(object sender, EventArgs e)
        {
            //******* disable BTScanLib
            btScanLib.OnScan -= btScanLib_OnScan;
            btScanLib.Disable();
            
            FrmPOKAYOKEMatching._Form_POKAYOKEMatchingInstance.Show();
            Bt.ScanLib.Control.btScanDisable();
            //this.Hide();
            this.Close();
        }


        /////////////////////////////////////////////////////////////
        /// Open
        /////////////////////////////////////////////////////////////
        private int openDB()
        {
            if (dbIdx > 0) return -1;
            dbIdx = Bt.FileLib.SQLite.btSQLiteOpen(new StringBuilder(dbFilePath));
            if (dbIdx > 0)
            {
                return 0;
            }
            else
            {

                return -1;
            }
        }

        /////////////////////////////////////////////////////////////
        /// Close
        /////////////////////////////////////////////////////////////
        private int closeDB()
        {
            if (dbIdx <= 0) return -1;
            int ret = Bt.FileLib.SQLite.btSQLiteClose(dbIdx);
            dbIdx = 0;
            if (ret == 0)
            {

                return 0;
            }
            else
            {

                return -1;
            }
        }



        /////////////////////////////////////////////////////////////
        /// Insert
        /////////////////////////////////////////////////////////////
        private void insertRecordPDS(string PDSNo)
        {
            openDB();

            string tableName = "Record_PDS";

            if (dbIdx <= 0) return;
            StringBuilder sql = new StringBuilder("INSERT INTO " + tableName + " VALUES('" + DateTime.Now.ToString("yyMMdd") + "', '" +
                                                                                                DateTime.Now.ToString("HHmmss") + "', '" +
                                                                                                FrmLogin._Form_LoginInstance.userName + "', '" +
                                                                                                FrmLogin._Form_LoginInstance.DevNO + "', '" +
                                                                                                PDSNo  + "');");

                       
            int ret = Bt.FileLib.SQLite.btSQLiteExecute(dbIdx, sql);
            if (ret == 0)
            {

            }
            else
            {

            }

            closeDB();


            InsertPDS(PDSNo);

        }

        private void InsertPDS(string PDSNo)
        {
            try
            {


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

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

                strSQL = "EXEC sp_insert_PDS @PDSNo = '" + PDSNo
                    + "' , @HTID = '" + FrmLogin._Form_LoginInstance.DevNO + "' , @userName = '" 
                    + FrmLogin._Form_LoginInstance.userName
                    + "' , @logDate = '" + DateTime.Now.ToString("yyMMdd") + "' , @logTime = '"
                    + DateTime.Now.ToString("HHmmss") + "'" ;

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


                objCmd.ExecuteNonQuery();

                objConn.Close();
                objConn = null;

            }
            catch (Exception)
            {

            }

        }

        private void button2_Click(object sender, EventArgs e)
        {
            int sel = listBox1.SelectedIndex;
            if (sel >= 0)
            {
                listBox1.Items.RemoveAt(sel);
            }

            if (listBox1.Items.Count == 0)
            {
                btnConfirm.Enabled = false;
            }
        }

    }
}