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

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\\SMPT";
        public string userName = "";
        public string DevNO = "HT01";

        public string DB_FILE =         "\\FlashDisk\\BT_FILES\\drv1\\SMPT\\HT_SMPT.db";
        public string SETTINGS_FILE =   "\\FlashDisk\\BT_FILES\\drv1\\SMPT\\Settings.csv";
        public string USER_INFO_FILE =  "\\FlashDisk\\BT_FILES\\drv1\\SMPT\\UserInfo.csv";
        public string LOG_DIR =         "\\FlashDisk\\BT_FILES\\drv1\\SMPT\\log\\";
        public string CSV_IMPORT_DIR =  "\\FlashDisk\\BT_FILES\\drv1\\SMPT\\in\\";
        public string CSV_EXPORT_DIR =  "\\FlashDisk\\BT_FILES\\drv1\\SMPT\\out\\";


        public string CSV_REMOTE_DIR =  ""; // control by server side

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

        private lib.BtScanLib btScanLib;


        //MsgWindow MsgWin;								// メッセージウインドウ

        //--------------------------------------------------------------
        // DLLImport
        //--------------------------------------------------------------
        //[DllImport("coredll.dll", EntryPoint = "DeleteObject")]
        //public static extern bool DeleteObject(IntPtr hObject);

        public Form_Login()
        {
            InitializeComponent();

            // 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;
            cmbUsername.SelectedIndex = cmbUsername.Items.IndexOf(user.Name);
            lblError.Visible = false;
            txtPassword.Focus();
        }

        private void txtPassword_KeyDown(object sender, KeyEventArgs e)
        {
            //MessageBox.Show(e.KeyCode.ToString(), "Alert");
            if (e.KeyCode.ToString() == "Return")
                btnLogin_Click(sender, e);
        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
            try
            {
                string tgtPass = passwordList[cmbUsername.SelectedIndex].Password;

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

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

                    Form frmD = new Form_Menu();
                    frmD.Show();
                    this.Hide();
                }
                else
                {
                    //PassErr err = new PassErr();
                    //err.Show();
                    //txtPassword.Text = "";

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

        private void Form_Login_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();
            removeExpireData();

        }

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

            using (var csv = new CsvReader(USER_INFO_FILE))
            {
                while ((tmp = csv.ReadRow()) != null)
                {
                    Users.User user = new Users.User()
                        {
                            Name = tmp[0],
                            Uid = tmp[1],
                            Password = tmp[2],
                            Dept = tmp[3],
                            Role = tmp[4]
                        };

                    userList.Add(tmp[1], user);

                    // Add to comboxBox username
                    cmbUsername.Items.Add(tmp[0]);
                    passwordList.Add(user);

                }

            }//using end

            //mngList = new List<List<string>>();
            //tmp = null;
            //using (var csv = new CsvReader("\\FlashDisk\\BT_FILES\\drv1\\SKT\\MngInfo.csv"))
            //{
            //    while ((tmp = csv.ReadRow()) != null)
            //    {
            //        mngList.Add(tmp);

            //    }

            //}//using end

            Settings = new List<List<string>>();
            tmp = null;
            using (var csv = new CsvReader(SETTINGS_FILE))
            {
                //Settings[0][0] = DevNO another stand by  for future
                while ((tmp = csv.ReadRow()) != null)
                {
                    Settings.Add(tmp);

                }

                try
                {
                    Form_Login._Form_LoginInstance.DevNO = Settings[0][0].Replace("\r", "");

                    // Set terminal name
                    IntPtr pTermId = Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(Char)) * (32 + 1));
                    byte[] chars = System.Text.Encoding.Unicode.GetBytes(Settings[0][0] + '\0');
                    Marshal.Copy(chars, 0, pTermId, chars.Length);
                    Bt.SysLib.Terminal.btSetHandyParameter(Bt.LibDef.BT_SYS_PRM_HTNAME, pTermId);


                    //IntPtr pTermId2 = Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(Char)) * (32 + 1));
                    //Bt.SysLib.Terminal.btGetHandyParameter(Bt.LibDef.BT_SYS_PRM_HTNAME, pTermId2);
                    //MessageBox.Show(Marshal.PtrToStringUni(pTermId), "Terminal Name");
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.ToString(), "Alert");
                }
            }//using end

        }

        private void removeExpireData()
        {
        }

        private void cmbUsername_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                lblUid.Text = passwordList[cmbUsername.SelectedIndex].Uid;
            }
            catch (Exception) { }
        }

        private void Exit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
    }
}