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.Net.Sockets;
using System.Net;
using SCAN.Data.DataAccess;
using SCAN.Data.DataModel;
using System.Runtime.InteropServices;
using CsvReadWrite;
using TowerLightSignal;
using Bt.CommLib;
using Bt.ScanLib;
using Bt;
using System.Threading;


namespace SCAN
{
    public partial class MsgLeaderScan : Form
    {

        [System.Runtime.InteropServices.DllImport("coredll.dll")]
        static extern short GetUserDefaultUILanguage();			


        public Dictionary<string, Users.User> userList;
        private lib.BtScanLib btScanLib;

        public MsgLeaderScan(string PartsNo, string LocationCode, string workingdate, Color color)
        {
            InitializeComponent();

            lblPartsNo.Text = PartsNo;
            lblLocationCode.Text = LocationCode;
            lblworkingdate.Text = workingdate;
       
        }

        private void ErrorForm_Load(object sender, EventArgs e)
        {
            if (System.Windows.Forms.Screen.PrimaryScreen.Bounds.Width == 240)
            {
                resolution.ScreenSize.VGAtoQVGA(this);
            }
            btScanLib = lib.BtScanLib.getInstance();
            btScanLib.OnScan += new SCAN.lib.ScanEventHandler(btScanLib_OnScan);
            btScanLib.Debug = false;
            btScanLib.Enable();
            // フォームの最大化・最小化ボタン非表示
            this.MaximizeBox = !this.MaximizeBox;
            this.MinimizeBox = !this.MinimizeBox;
            SendSignalTowerlight(1);


            //StringBuilder filenameSet = new StringBuilder("\\FlashDisk\\BT_FILES\\drv1\\ACME\\OCRSettingBarcodeOnly.ini");
            //int ret = Setting.btScanLoadOCRConfig(filenameSet);
            //Bt.ScanLib.Utility.btScanSetServiceEnable(0);


            //string sName = "";
            //string sAddr = "48A493155B09";// Form_Login._Form_LoginInstance.Settings[0][2]; ;
        
            //Int32 ret2 = 0;



            //ret2 = Bluetooth.btBluetoothOpen();
            ////Thread.Sleep(500);
            //BiCom.btBiComDisconnect();

            //LibDef.BT_BLUETOOTH_TARGET target = new LibDef.BT_BLUETOOTH_TARGET();
            //target.name = sName;
            //target.addr = sAddr;
            //ret2 = BiCom.btBiComConnect(target, 30000);


            //if (ret2 != LibDef.BT_OK)
            //{

            //    MessageBox.Show("btBluetoothSPPConnect error ret[" + ret2 + "]");
            //    btScanLib.OnScan -= btScanLib_OnScan;
            //    btScanLib.Disable();


            //    Form frm = new Form_Matching(lblmodel.Text, lblserialatproduct.Text, lblserialatbox.Text);
            //    frm.Show();
            //    this.Close();
         
            //}


            //try  // ส่งข้อมูลไปยัง tower light
            //{
            //    SendSignalTowerlight(1);
            

            //}
            //catch (Exception ex)
            //{
            //    MessageBox.Show(ex.Message);
            //}
            //finally
            //{

            //}



        }
        private void SendSignalTowerlight(Int32 _Channel)
        {
            int ret = 0;

            UInt32 io = 0;
            //if (_Channel == 1)
            //{ io += LibDef.BT_BICOM_STATUS_1; }
            //if (_Channel == 2)
            //{ io += LibDef.BT_BICOM_STATUS_2; }
            //if (_Channel == 3)
            //{ io += LibDef.BT_BICOM_STATUS_3; }


            io += LibDef.BT_BICOM_STATUS_2;
            io += LibDef.BT_BICOM_STATUS_3; 

            string strBuf = "";
            int ssize = 0;
            IntPtr pBufSet;
            byte[] bBuf = new byte[] { };

            strBuf = "0123456789"; // send data

            if (strBuf.Length > 0)
            {
              
                bBuf = System.Text.Encoding.GetEncoding(GetCodePage()).GetBytes(strBuf);
                ssize = bBuf.Length;
                pBufSet = Marshal.AllocCoTaskMem(bBuf.Length);
                Marshal.Copy(bBuf, 0, pBufSet, ssize);

                ret = BiCom.btBiComSend(pBufSet, Convert.ToUInt32(ssize), Convert.ToUInt32(io)); // BiCom.btBiComSend(pBufSet, ssize, io);
                if (ret != LibDef.BT_OK)
                    MessageBox.Show("Error:" + ret);
                Marshal.FreeCoTaskMem(pBufSet);
            }


        }

        private int GetCodePage()
        {
            short lang = GetUserDefaultUILanguage();
            if ((lang == 0x804))
                return 936; // Simplified Chinese
            else if ((lang == 0x411))
                return 932;  // Japanese
            else if ((lang == 0x409))
                return 0; // English(US)
            else
                return 0;
        }


        void btScanLib_OnScan(string result)
        {




            // check employee leader
            userList = Users.GetInstance();
            List<string> tmp = null;


            using (var csv = new CsvReader(Form_Login._Form_LoginInstance.USER_INFO_FILE))
            {
                Dictionary<string, string> comboSource = new Dictionary<string, string>();

                while ((tmp = csv.ReadRow()) != null)
                {

                    if (tmp[1].Trim() == result.Trim())
                    {

                        if (tmp[4].Trim() == "head")
                        {

                            ProductMatching objProductMatching = new ProductMatching();
                            objProductMatching.WorkDate = lblworkingdate.Text;
                            objProductMatching.PartsNo = lblPartsNo.Text;
                            objProductMatching.LocationCode = lblLocationCode.Text;
                            objProductMatching.UserID = Form_Login._Form_LoginInstance.userName;
                            objProductMatching.Status = "NG";

                            StringBuilder sqlInsert = AddAccess.Instant.getAddScanData(objProductMatching);
                            int dbIdx = lib.SqliteDb.openDB(Form_Login._Form_LoginInstance.DB_FILE);
                            int retIns = Bt.FileLib.SQLite.btSQLiteExecute(dbIdx, sqlInsert);




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

                            //BiCom.btBiComDisconnect();
                   

                            Form frm = new Form_Matching(lblPartsNo.Text, lblLocationCode.Text);
                            frm.Show();
                            this.Close();

                           
                        }
                        else
                        {
                            lblalert.Text = "Data is not leader code";
                            //MessageBox.Show("Data is not leader code");
                            return;
                        }
                       
                    }
                    else
                    {
                        lblalert.Text = "Data is not found";
                        //MessageBox.Show("Data is not found");
                     
                    }


                }




            }
  
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Bluetooth.btBluetoothClose();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            SendSignalTowerlight(1);
        }

    
     
    }
}