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 SCAN.Data.DataAccess;
using Bt.ScanLib;

using System.Runtime.InteropServices;
using CsvReadWrite;
using SCAN.lib;
using Bt.CommLib;

using Bt;

namespace SCAN
{
    public partial class Form_Login : Form
    {

        public static Form_Login _Form_LoginInstance;
        private lib.LogWriter logger = lib.LogWriter.getInstance();
        public String AppPath = "\\FlashDisk\\BT_FILES\\drv1\\HT_WeightDataToPrint";
        public string userName = "";
        public string DevNO = "HT01";

        public string DB_FILE = "\\FlashDisk\\BT_FILES\\drv1\\HT_WeightDataToPrint\\HT_WeightDataToPrint.db";

        //public string SETTINGS_FILE = "\\FlashDisk\\BT_FILES\\drv1\\NMB_PLC\\Settings.csv";
        public string USER_INFO_FILE = "\\FlashDisk\\BT_FILES\\drv1\\HT_WeightDataToPrint\\in\\UserInfo.csv";
        public static string MASTER_FILE = "\\FlashDisk\\BT_FILES\\drv1\\HT_WeightDataToPrint\\in\\Master.csv";
        public string LOG_DIR = "\\FlashDisk\\BT_FILES\\drv1\\HT_WeightDataToPrint\\log\\";
        public string CSV_IMPORT_DIRTank_and_material = "\\FlashDisk\\BT_FILES\\drv1\\HT_WeightDataToPrint\\in\\";

        public string CSV_EXPORT_DIR = "\\FlashDisk\\BT_FILES\\drv1\\HT_WeightDataToPrint\\out\\";
        public string CSV_REMOTE_DIR = ""; // control by server side

        public Dictionary<string, Users.User> userList;
        public List<List<string>> mngList;
        public List<List<string>> Settings;
        public List<List<string>> SettingsIP;

        public static string weightData = string.Empty;
        public static bool IsCloseShare = false;
        public static bool IsContinue = false;
        public static bool IsAppExit = false;

        private lib.BtScanLib btScanLib;


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

        public Form_Login()
        {
            InitializeComponent();


            lib.LogWriter.Disable = false;    // leave out this comment to open LOG writer

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

         
        }

        void btScanLib_OnScan(string result)
        {

            //Users.User user;
            //if (!userList.TryGetValue(result, out user))
            //{
           
            //    // Alert
            //    lib.BtSysLib.vibrateOn(100, 1);
            //    lib.BtSysLib.buzzerOn(400, 1);

            //    lblError.Visible = true;
            //    return;
            //}

            lblUid.Text = result;
            txtUsername.Text = result.Trim();
            txtPassword.Focus();
            lblError.Visible = false;
        }

        private void btnLogin_Click(object sender, EventArgs e)
        {

            try
            {

                string tgtPass = userList[txtUsername.Text].Password;

                if (tgtPass == txtPassword.Text)
                {
                    this.userName = txtUsername.Text;
                    lblError.Visible = false;

                    // disable BTScanLib
                    btScanLib.OnScan -= btScanLib_OnScan;
                    btScanLib.Disable();
                    //if (connectbluetooth())
                    //{
                    Form frmD = new Form_Menu();
                    frmD.Show();
                    this.Hide();
                    //}
                }
                else
                {
                    //PassErr err = new PassErr();
                    //err.Show();
                    //txtPassword.Text = "";

                    lblError.Visible = true;
                }
            }
            catch (Exception ee)
            {
                lblError.Visible = true;
            }
        }
               


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

            _Form_LoginInstance = this;



         

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

            SetUserInfo();
     

        }

        public void SetUserInfo()
        {
            //CSV read
            userList = Users.GetInstance();
            List<string> tmp = null;


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

                while ((tmp = csv.ReadRow()) != null)
                {
                  
                    userList.Add(tmp[1],
                        new Users.User()
                        {
                            No = tmp[0],
                            Uid = tmp[1],
                            Password = tmp[2],
                            Fullname = tmp[3],
                            Role = tmp[4]
                        }
                        );

                    comboSource.Add(tmp[0], tmp[1] );
                }


                txtUsername.DataSource = new BindingSource(comboSource, null);
                txtUsername.DisplayMember = "Value";
                txtUsername.ValueMember = "Key";


            }//using end



            Settings = new List<List<string>>();
            tmp = null;
            using (var csv = new CsvReader("\\FlashDisk\\BT_FILES\\drv1\\HT_WeightDataToPrint\\in\\Settings.csv"))
            {//mysql
                //setting list comName, WatchCnt, RetryCnt;
                //SettingList[8]no 0 timer interval, 1 share id, 2, share pass, 3 upload path 4 share dir
                while ((tmp = csv.ReadRow()) != null)
                {
                    Settings.Add(tmp);

                }

            }//using end


            SettingsIP = new List<List<string>>();
            tmp = null;
            using (var csv = new CsvReader("\\FlashDisk\\BT_FILES\\drv1\\HT_WeightDataToPrint\\in\\SettingsIP.csv"))
            {//mysql
                //setting list comName, WatchCnt, RetryCnt;
                //SettingList[8]no 0 timer interval, 1 share id, 2, share pass, 3 upload path 4 share dir
                while ((tmp = csv.ReadRow()) != null)
                {
                    SettingsIP.Add(tmp);

                }

            }//using end


        }

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

                case "Return":
                    btnLogin_Click(sender, e);

                    break;

                case "F4":

                    btnAppClose_Click_1(sender, e);

                    break;

            }
        }

       

        private void btnAppClose_Click_1(object sender, EventArgs e)
        {
            try
            {
                Bluetooth.btBluetoothClose();
                Application.Exit();
                this.Dispose();
                this.Close();

            }
            catch (Exception ex)
            {

            }
        }

        private void Form_Login_Closing(object sender, CancelEventArgs e)
        {
            
        }

        private void Form_Login_Closed(object sender, EventArgs e)
        {

        }




    }
}