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

using SCAN.lib;

namespace SCAN
{
    public partial class Form_Matching : Form
    {
        [System.Runtime.InteropServices.DllImport("coredll.dll")]
        static extern short GetUserDefaultUILanguage();			

        
        TowerlightSignal objTowerlight = new TowerlightSignal();

        public static Form_Matching Form_Instant_Matching;

        public string Master_FILE = "\\FlashDisk\\BT_FILES\\drv1\\HT_WeightDataToPrint\\in\\Master.csv";
        public List<List<string>> MasterList;
        public string locationMaster;

        private lib.BtScanLib btScanLib;
        
        public Form_Matching()
        {
            InitializeComponent();

            btScanLib = lib.BtScanLib.getInstance();
            btScanLib.OnScan += new SCAN.lib.ScanEventHandler(btScanLib_OnScan);
            btScanLib.Debug = false;
            btScanLib.Enable();
            Form_Instant_Matching = this;

            tbxWorkingDate.Text = myGlobals.matchingDate.ToString("dd/MM/yyyy");

            InitialData();
            //connectbluetooth();
            //Bluetooth.btBluetoothClose();
            //Bluetooth.btBluetoothOpen();
         
        }

        public Form_Matching(string PartsNo, string LocationCode)
        {
            InitializeComponent();


            btScanLib = lib.BtScanLib.getInstance();
            btScanLib.OnScan += new SCAN.lib.ScanEventHandler(btScanLib_OnScan);
            btScanLib.Debug = false;
            btScanLib.Enable();
            Form_Instant_Matching = this;

            tbxWorkingDate.Text = myGlobals.matchingDate.ToString("dd/MM/yyyy");


            tbxPartsNo.Text = PartsNo;
            tbxLocationCode.Text = string.Empty;
            tbxLocationCode.Focus();
            tbxLocationCode.BackColor = Color.GreenYellow;

       
            //connectbluetooth();
        }


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


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

            SetMaster();

        }

        private void InitialData()
        {
         
            tbxPartsNo.Focus();
            tbxPartsNo.BackColor = Color.GreenYellow;

           
        }
        private void connectbluetooth()
        {
            string sName = "";
            string sAddr = Form_Login._Form_LoginInstance.Settings[0][2]; ;

            Bluetooth.btBluetoothOpen();
            BiCom.btBiComDisconnect();

            LibDef.BT_BLUETOOTH_TARGET target = new LibDef.BT_BLUETOOTH_TARGET();
            target.name = sName;
            target.addr = sAddr;

            Int32 ret;
            ret = BiCom.btBiComConnect(target, 30000);
            if (ret != LibDef.BT_OK)
            {
                MessageBox.Show("Error Connect Bluetooth");
                btScanLib.OnScan -= btScanLib_OnScan;
                btScanLib.Disable();
                BiCom.btBiComDisconnect();

                Form_Menu._Form_MenuInstance.Show();
                this.Close();
            } 
        
        }

        public void SetMaster()
        {
            //CSV read
            List<string> tmp = null;
            MasterList = new List<List<string>>();
            locationMaster = string.Empty;

            using (var csv = new CsvReader(Master_FILE))
            {
                Dictionary<string, string> comboSource = new Dictionary<string, string>();

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

                    MasterList.Add(tmp);
                   
                }


            }//using end



         
        }
        
        private void Clear()
        {
            tbxPartsNo.Focus();
            tbxPartsNo.BackColor = Color.GreenYellow;
            tbxLocationCode.BackColor = Color.White;
            lblStatus.BackColor = Color.Silver;


            lblStatus.Text = string.Empty;
            tbxPartsNo.Text = string.Empty;
            tbxLocationCode.Text = string.Empty;
            
        }

        private void ClearLocationCode()
        {
            tbxLocationCode.Focus();
            tbxLocationCode.BackColor = Color.GreenYellow;
            lblStatus.BackColor = Color.Silver;

            lblStatus.Text = string.Empty;
            tbxLocationCode.Text = string.Empty;

        }

        void btScanLib_OnScan(string result)
        {
            if (tbxPartsNo.Text.Trim() == string.Empty && tbxLocationCode.Text.Trim() == string.Empty)
            {
                if (result.Trim().Contains("M") && result.Trim() != "Parts no")
                {
                    tbxPartsNo.Text = result;

                    locationMaster = string.Empty;

                    foreach (var item in MasterList)
                    {
                        if (item[1] == result)
                        {
                            locationMaster = item[2];
                        }
                    }

                    tbxLocationCode.Focus();
                    tbxPartsNo.BackColor = Color.White;
                    tbxLocationCode.BackColor = Color.GreenYellow;
                    return;

                }
                else
                {
                    MessageBox.Show("format error");
                    return;
                }
           
            }
            
            if (tbxPartsNo.Text.Trim() != string.Empty && tbxLocationCode.Text.Trim() == string.Empty)
            {
                if (result.Trim().Length != 4 || result.Trim() == "Location code")
                {
                    MessageBox.Show("format error");
                    return;
                }
                tbxLocationCode.Text = result;

                // matching
                if (tbxLocationCode.Text.Trim() == locationMaster) // matching success
                {
                    ProductMatching objProductMatching = new ProductMatching();
                    objProductMatching.WorkDate = tbxWorkingDate.Text;
                    objProductMatching.PartsNo = tbxPartsNo.Text;
                    objProductMatching.LocationCode = tbxLocationCode.Text;
                    objProductMatching.UserID = Form_Login._Form_LoginInstance.userName;
                    objProductMatching.Status = "OK";

                    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);


                    lblStatus.BackColor = Color.Green;
                    lblStatus.Text = "OK";
                    Form_Instant_Matching.Update();


                
                    //SendSignalTowerlight(3);
                    SendSignalPLC(1, tbxLocationCode.Text.Trim());


                    MessageBox.Show("OK");


                    Thread.Sleep(400);
                    Clear();


                    Form_Instant_Matching.Update();



                }
                else
                {

                    ProductMatching objProductMatching = new ProductMatching();
                    objProductMatching.WorkDate = tbxWorkingDate.Text;
                    objProductMatching.PartsNo = tbxPartsNo.Text;
                    objProductMatching.LocationCode = tbxLocationCode.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);


                    lblStatus.BackColor = Color.Red;
                    lblStatus.Text = "NG";
                    Form_Instant_Matching.Update();



                    //SendSignalTowerlight(3);
                    SendSignalPLC(0, tbxLocationCode.Text.Trim());

                    MessageBox.Show("NG");

                    Thread.Sleep(400);
                    //ClearLocationCode();
                    Clear();


                    Form_Instant_Matching.Update();


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


                    //Form frm = new MsgLeaderScan(tbxPartsNo.Text, tbxLocationCode.Text, tbxWorkingDate.Text, Color.Red);
                    //frm.Show();
                    //this.Close();

                    //return;
                    //----------------

                                     
                }
                return;
            }
   

        }

        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_1; 

            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 void SendSignalPLC(Int32 _Channel, string _Location)
        {
            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_1;

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

            if (_Channel == 1)
            {
                //strBuf = "DMR50000"; // send data OK Keyence
                strBuf = "OK" + _Location; // send data OK Mitsu
            }
            else if (_Channel == 0)
            {
                //strBuf = "DMR50001"; // send data NG Keyence
                strBuf = "NG" + _Location; // send data NG Mitsu
            }
            

            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);
                MessageBox.Show("Please scan again");
                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;
        }

    
        private bool SendDatatest(string data)
        {
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPAddress ipAdd = System.Net.IPAddress.Parse("192.168.1.131");
            IPEndPoint remoteEP = new IPEndPoint(ipAdd, 1002);

            socket.Connect(remoteEP);

            byte[] byData = System.Text.Encoding.ASCII.GetBytes(data);
            socket.Send(byData);



            socket.Close();
            return true;
        }


        private void btnMainMenu_Click(object sender, EventArgs e)
        {
            btScanLib.OnScan -= btScanLib_OnScan;
            btScanLib.Disable();

            //BiCom.btBiComDisconnect();
            Form_Menu._Form_MenuInstance.Show();
            this.Close();
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            Clear();
        }

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

                case "F1":
                    btnMainMenu_Click(sender, e);

                    break;
              
                case "F4":

                    btnClear_Click(sender, e);

                    break;
            }

        }

        private void tbxLocationCode_TextChanged(object sender, EventArgs e)
        {

        }

   
    }
}