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 INT_LKD_2.DataStore;
using INT_LKD_2.Part11_UserManager;
using INT_LKD_2.DialogForms;

namespace INT_LKD_2.Forms
{
    public partial class DialogFormLogOn : Form
    {
        #region Field
        private FormMain m_ParentForm;
        private bool IsLoginMode;
        private bool IsChangePassword;
        #endregion

        #region Constructor
        public DialogFormLogOn(FormMain parent, bool login, bool changePass)
        {
            InitializeComponent();

            this.ParentForm = parent;
            this.IsLoginMode = login;
            this.IsChangePassword = changePass;

            if (this.IsChangePassword == false)
            {
                this.InitializeDesignForLogin();

                this.textBoxID.PasswordChar = default(char);
            }
            else
            {
                this.InitializeDesignForChangePassword();

                this.textBoxID.PasswordChar = '*';
            }

            this.InitializeControl();
            this.DefaultSetting();
        }
        #endregion

        #region Property
        public FormMain ParentForm
        {
            get { return this.m_ParentForm; }
            private set { this.m_ParentForm = value; }
        }
        #endregion

        #region Method
        private string ReturnUserStatus(int num)
        {
            string ret = "";

            switch (num)
            {
                case 1:
                    ret = "ID_Not found";
                    break;
                case 2:
                    ret = "ID_Duplication";
                    break;
                case 3:
                    ret = "ID_Too short";
                    break;
                case 4:
                    ret = "ID_Too long";
                    break;
                case 5:
                    ret = "ID_Consecutive or duplicate char";
                    break;
                case 6:
                    ret = "ID_Invalid char";
                    break;
                case 7:
                    ret = "ID_Lock";
                    break;
                case 8:
                    ret = "PW_Duplicate prev PW";
                    break;
                case 9:
                    ret = "PW_Too short";
                    break;
                case 10:
                    ret = "PW_Too long";
                    break;
                case 11:
                    ret = "PW_Consecutive or duplicate char";
                    break;
                case 12:
                    ret = "PW_Invalid char";
                    break;
                case 13:
                    ret = "PW_Not include char";
                    break;
                case 14:
                    ret = "PW_Incorrect";
                    break;
                case 15:
                    ret = "PW_Lock";
                    break;
                case 16:
                    ret = "PW_Over expire period";
                    break;
                case 17:
                    ret = "ID_Over expire period";
                    break;
                case 18:
                    ret = "Auto logout";
                    break;
                default:
                    ret = "";
                    break;
            }

            return ret;
        }

        private void InitializeDesign()
        {

        }
        private void InitializeControl()
        {
            this.textBoxID.Text = "";
            this.textBoxPassword.Text = "";
            this.textBoxID.Focus();

            int x = 0, y = 0;

            x = Screen.PrimaryScreen.Bounds.Width / 2 - this.Size.Width / 2;
            y = Screen.PrimaryScreen.Bounds.Height / 2 - this.Size.Height / 2;

            this.Location = new Point(x, y);
            this.Size = new Size(652, 402);

            //this.smartKeyboard.HanYoungKeyToggle();
            this.smartKeyboard.HanYoungKeyDisable = true;
            this.smartKeyboard.KeyboardType = SmartX.SmartKeyboard.KEYBOARDTYPES.NORMAL;
            this.smartKeyboard.Show();
        }
        private void DefaultSetting()
        {

        }

        private void InitializeDesignForLogin()
        {
            if (this.ParentForm.SystemConfig.LANGUAGE == Define.E_LanguageID.English)
            {
                this.smartGroupBox1.Text = "User Login";
                this.labelTitleID.Text = "ID";
                this.labelTitlePassword.Text = "Password";
            }
            else
            {
                this.smartGroupBox1.Text = "로그인";
                this.labelTitleID.Text = "ID";
                this.labelTitlePassword.Text = "비밀번호";
            }
        }
        private void InitializeDesignForChangePassword()
        {
            if (this.ParentForm.SystemConfig.LANGUAGE == Define.E_LanguageID.English)
            {
                this.smartGroupBox1.Text = "Change Password";
                this.labelTitleID.Text = "New";
                this.labelTitlePassword.Text = "Verify";
            }
            else
            {
                this.smartGroupBox1.Text = "비밀번호 변경";
                this.labelTitleID.Text = "새 비밀번호";
                this.labelTitlePassword.Text = "비밀번호 확인";
            }
        }

        private void LogOn()
        {
            UserManager.UserMgr_user_info_t userInfo = new UserManager.UserMgr_user_info_t();

            if (this.textBoxID.Text == "")
            {
                this.ParentForm.SetTrackingHistoryData(Define.E_TrackingOperation.Login, "Fail : ID blank");

                // ID : 6~20자 입력 하세요
                DialogFormMessage myMsg = new DialogFormMessage(null, 3, this.ParentForm.SystemConfig.LANGUAGE);
                myMsg.ShowDialog();

                return;
            }
            if (this.textBoxPassword.Text == "")
            {
                this.ParentForm.SetTrackingHistoryData(Define.E_TrackingOperation.Login, "Fail : PW blank");

                // PASSWORD : 6~20자 입력 하세요
                DialogFormMessage myMsg = new DialogFormMessage(null, 9, this.ParentForm.SystemConfig.LANGUAGE);
                myMsg.ShowDialog();

                return;
            }

            if (this.textBoxID.Text == "admin00" && this.textBoxPassword.Text == "admin20090810")
            {
                DialogFormYesNo dlg = new DialogFormYesNo(this.ParentForm.SystemConfig.LANGUAGE, 18);
                if (dlg.ShowDialog() == DialogResult.Yes)
                {
                    this.ParentForm.ChildFormMainDisplay.ChangeID = this.textBoxID.Text;
                    this.DialogResult = DialogResult.Abort;
                    this.Close();
                }
                return;
            }

            UserManager.UserManager_UserLoginDirect(this.textBoxID.Text, this.textBoxPassword.Text, ref userInfo);

            //Console.Write("\n" + string.Format("userInfo.fFirstPW {0:yyyy-MM-dd HH:mm:ss}: {1}", DateTime.Now, userInfo.fFirstPW));
            //Console.Write("\n" + string.Format("userInfo.status {0:yyyy-MM-dd HH:mm:ss}: {1}", DateTime.Now, userInfo.status));

            if (userInfo.status == 0 && userInfo.fFirstPW == 0)
            {
                //MessageBox.Show("로그인 성공");

                #region 로그인 성공
                if (userInfo.active_level == 1)
                    this.ParentForm.CurrentSystemStatus.CurrentUser.Group = Define.E_UserGroup.Level1;
                else if (userInfo.active_level == 2)
                    this.ParentForm.CurrentSystemStatus.CurrentUser.Group = Define.E_UserGroup.Level2;
                else if (userInfo.active_level == 3)
                    this.ParentForm.CurrentSystemStatus.CurrentUser.Group = Define.E_UserGroup.Level3;
                else if (userInfo.active_level == 9)
                    this.ParentForm.CurrentSystemStatus.CurrentUser.Group = Define.E_UserGroup.Admin;
                else if (userInfo.active_level == 10)
                    this.ParentForm.CurrentSystemStatus.CurrentUser.Group = Define.E_UserGroup.Developer;

                this.ParentForm.CurrentSystemStatus.CurrentUser.ID = userInfo.user_id;
                this.ParentForm.CurrentSystemStatus.CurrentUser.Password = userInfo.user_pw;

                this.ParentForm.CurrentSystemStatus.CurrentUser.ExpireId = userInfo.id_expire_period;
                this.ParentForm.CurrentSystemStatus.CurrentUser.ExpirePassword = userInfo.password_expire_period;

                DateTime time = DateTime.ParseExact(userInfo.password_register_date.GetDateTime(), "yyyyMMddHHmmss", null);
                this.ParentForm.CurrentSystemStatus.CurrentUser.DatePasswordRegister = time;
                time = DateTime.ParseExact(userInfo.id_login_date.GetDateTime(), "yyyyMMddHHmmss", null);
                this.ParentForm.CurrentSystemStatus.CurrentUser.DateIdLogin = time;
                time = DateTime.ParseExact(userInfo.id_expire_date.GetDateTime(), "yyyyMMddHHmmss", null);
                this.ParentForm.CurrentSystemStatus.CurrentUser.DateIdExpire = time;
                time = DateTime.ParseExact(userInfo.password_expire_date.GetDateTime(), "yyyyMMddHHmmss", null);
                this.ParentForm.CurrentSystemStatus.CurrentUser.DatePasswordExpire = time;

                this.ParentForm.CurrentSystemStatus.CurrentUser.IsLockAccount = userInfo.id_flock_status == 0 ? false : true;
                this.ParentForm.CurrentSystemStatus.CurrentUser.IsLockPassword = userInfo.password_flock_status == 0 ? false : true;
                this.ParentForm.CurrentSystemStatus.CurrentUser.IsAdmin = userInfo.fadmin == 0 ? false : true;
                this.ParentForm.CurrentSystemStatus.CurrentUser.ActiveLevel = userInfo.active_level;
                this.ParentForm.CurrentSystemStatus.CurrentUser.IsFirstPassword = userInfo.fFirstPW;
                #endregion

                this.ParentForm.SetTrackingHistoryData(Define.E_TrackingOperation.Login, "Success");

                this.DialogResult = DialogResult.OK;
                this.Close();
            }
            else if (userInfo.fFirstPW == 1)
            {
                this.ParentForm.SetTrackingHistoryData(Define.E_TrackingOperation.Login, "First login", this.textBoxID.Text);

                // 최초 로그인 시 비밀번호 변경
                this.ParentForm.ChildFormMainDisplay.ChangeID = this.textBoxID.Text;
                this.DialogResult = DialogResult.Abort;
                this.Close();
            }
            else if (userInfo.status == 14) // password error
            {
                if (this.textBoxID.Text == "admin00")
                {
                    // 비밀번호를 확인하세요
                    DialogFormMessage myMsg = new DialogFormMessage(null, userInfo.status, this.ParentForm.SystemConfig.LANGUAGE);
                    myMsg.ShowDialog();

                    return;
                }

                if (userInfo.login_fail_count < this.ParentForm.SystemConfig.NUMBER_OF_LOGIN_FAILURE)
                {
                    // 비밀번호 n회 오류입니다
                    // n회 오류 시, 계정이 잠금처리됩니다.
                    DialogFormMessage myMsg = new DialogFormMessage(null, userInfo.status, userInfo.login_fail_count,
                        this.ParentForm.SystemConfig.NUMBER_OF_LOGIN_FAILURE, this.ParentForm.SystemConfig.LANGUAGE);
                    myMsg.ShowDialog();

                    this.ParentForm.SetTrackingHistoryData(Define.E_TrackingOperation.Login, string.Format("Fail : PW error {0}", userInfo.login_fail_count), this.textBoxID.Text);
                }
                else
                {
                    // 계정이 잠금처리 되었습니다.
                    // 관리자에게 문의하세요.
                    DialogFormMessage myMsg = new DialogFormMessage(null, 19, this.ParentForm.SystemConfig.LANGUAGE);
                    myMsg.ShowDialog();

                    UserManager.UserManager_UserLoginFailLockSet(this.textBoxID.Text);

                    this.ParentForm.SetTrackingHistoryData(Define.E_TrackingOperation.Login, "Account lock", this.textBoxID.Text);
                }
            }
            else
            {
                DialogFormMessage myMsg = new DialogFormMessage(null, userInfo.status, this.ParentForm.SystemConfig.LANGUAGE);
                myMsg.ShowDialog();

                // 비밀번호 만료 시
                if (userInfo.status == 15)
                {
                    this.ParentForm.SetTrackingHistoryData(Define.E_TrackingOperation.Login, "Password expiration", this.textBoxID.Text);

                    this.ParentForm.ChildFormMainDisplay.ChangeID = this.textBoxID.Text;

                    this.DialogResult = DialogResult.Abort;
                    this.Close();
                }
                else
                {
                    this.ParentForm.SetTrackingHistoryData(Define.E_TrackingOperation.Login, "Fail : " + this.ReturnUserStatus(userInfo.status), this.textBoxID.Text);
                }
            }
        }
        private void ChangePassword()
        {
            int ret = 0;
            string id = "", pass = "";
            UserManager.UserMgr_user_info_t userInfo = new UserManager.UserMgr_user_info_t();

            if (this.textBoxID.Text == "")
            {
                this.ParentForm.SetTrackingHistoryData(Define.E_TrackingOperation.Login, "Fail : TextBox1 blank");

                // New Password : 6~20자 입력 하세요
                DialogFormMessage myMsg = new DialogFormMessage(null, 9, this.ParentForm.SystemConfig.LANGUAGE);
                myMsg.ShowDialog();

                return;
            }
            if (this.textBoxPassword.Text == "")
            {
                this.ParentForm.SetTrackingHistoryData(Define.E_TrackingOperation.Login, "Fail : TextBox2 blank");

                // New Password Confirmation : 6~20자 입력 하세요
                DialogFormMessage myMsg = new DialogFormMessage(null, 9, this.ParentForm.SystemConfig.LANGUAGE);
                myMsg.ShowDialog();

                return;
            }
            if (this.textBoxID.Text.Equals(this.textBoxPassword.Text) == false)
            {
                this.ParentForm.SetTrackingHistoryData(Define.E_TrackingOperation.Login, "Fail : Diffrent char");

                // 비밀번호를 확인하세요
                DialogFormMessage myMsg = new DialogFormMessage(null, 14, this.ParentForm.SystemConfig.LANGUAGE);
                myMsg.ShowDialog();

                return;
            }

            if (this.IsLoginMode == true)
                id = this.ParentForm.CurrentSystemStatus.CurrentUser.ID;
            else
                id = this.ParentForm.ChildFormMainDisplay.ChangeID;

            pass = this.textBoxID.Text;
            ret = UserManager.UserManager_UserModifyPWDirect(id, pass);

            // 비밀번호 변경이 완료 되면 로그인 시도
            if (ret == 0)
            {
                UserManager.UserManager_UserLoginDirect(id, pass, ref userInfo);

                if (userInfo.status == 0)
                {
                    //MessageBox.Show("로그인 성공");

                    #region 로그인 성공
                    if (userInfo.active_level == 1)
                        this.ParentForm.CurrentSystemStatus.CurrentUser.Group = Define.E_UserGroup.Level1;
                    else if (userInfo.active_level == 2)
                        this.ParentForm.CurrentSystemStatus.CurrentUser.Group = Define.E_UserGroup.Level2;
                    else if (userInfo.active_level == 3)
                        this.ParentForm.CurrentSystemStatus.CurrentUser.Group = Define.E_UserGroup.Level3;
                    else if (userInfo.active_level == 9)
                        this.ParentForm.CurrentSystemStatus.CurrentUser.Group = Define.E_UserGroup.Admin;
                    else if (userInfo.active_level == 10)
                        this.ParentForm.CurrentSystemStatus.CurrentUser.Group = Define.E_UserGroup.Developer;

                    this.ParentForm.CurrentSystemStatus.CurrentUser.ID = userInfo.user_id;
                    this.ParentForm.CurrentSystemStatus.CurrentUser.Password = userInfo.user_pw;

                    this.ParentForm.CurrentSystemStatus.CurrentUser.ExpireId = userInfo.id_expire_period;
                    this.ParentForm.CurrentSystemStatus.CurrentUser.ExpirePassword = userInfo.password_expire_period;

                    DateTime time = DateTime.ParseExact(userInfo.password_register_date.GetDateTime(), "yyyyMMddHHmmss", null);
                    this.ParentForm.CurrentSystemStatus.CurrentUser.DatePasswordRegister = time;
                    time = DateTime.ParseExact(userInfo.id_login_date.GetDateTime(), "yyyyMMddHHmmss", null);
                    this.ParentForm.CurrentSystemStatus.CurrentUser.DateIdLogin = time;
                    time = DateTime.ParseExact(userInfo.id_expire_date.GetDateTime(), "yyyyMMddHHmmss", null);
                    this.ParentForm.CurrentSystemStatus.CurrentUser.DateIdExpire = time;
                    time = DateTime.ParseExact(userInfo.password_expire_date.GetDateTime(), "yyyyMMddHHmmss", null);
                    this.ParentForm.CurrentSystemStatus.CurrentUser.DatePasswordExpire = time;

                    this.ParentForm.CurrentSystemStatus.CurrentUser.IsLockAccount = userInfo.id_flock_status == 0 ? false : true;
                    this.ParentForm.CurrentSystemStatus.CurrentUser.IsLockPassword = userInfo.password_flock_status == 0 ? false : true;
                    this.ParentForm.CurrentSystemStatus.CurrentUser.IsAdmin = userInfo.fadmin == 0 ? false : true;
                    this.ParentForm.CurrentSystemStatus.CurrentUser.ActiveLevel = userInfo.active_level;
                    this.ParentForm.CurrentSystemStatus.CurrentUser.IsFirstPassword = userInfo.fFirstPW;
                    #endregion

                    this.ParentForm.SetTrackingHistoryData(Define.E_TrackingOperation.Login, "Success");

                    this.DialogResult = DialogResult.OK;
                    this.Close();
                }
                else
                {
                    this.ParentForm.SetTrackingHistoryData(Define.E_TrackingOperation.Login, "Fail : " + this.ReturnUserStatus(ret));

                    DialogFormMessage myMsg = new DialogFormMessage(null, ret, this.ParentForm.SystemConfig.LANGUAGE);
                    myMsg.ShowDialog();
                }
            }
            else
            {
                this.ParentForm.SetTrackingHistoryData(Define.E_TrackingOperation.Login, "Failure change password");

                // 비밀번호 변경 실패 시 메시지??
                DialogFormMessage myMsg = new DialogFormMessage(null, ret, this.ParentForm.SystemConfig.LANGUAGE);
                myMsg.ShowDialog();
            }
        }
        #endregion

        #region Event Handler
        private void buttonLogOn_Click(object sender, EventArgs e)
        {
            // Automatic Logout Reset
            this.ParentForm.ChildFormMainDisplay.Part11AutomaticLogoutReset();

            if (this.IsChangePassword == false)
                this.LogOn();
            else
                this.ChangePassword();
        }
        private void buttonCancel_Click(object sender, EventArgs e)
        {
            // Automatic Logout Reset
            this.ParentForm.ChildFormMainDisplay.Part11AutomaticLogoutReset();

            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }

        private void textBoxID_GotFocus(object sender, EventArgs e)
        {
            // Automatic Logout Reset
            this.ParentForm.ChildFormMainDisplay.Part11AutomaticLogoutReset();

            this.smartKeyboard.TargetInputObject = this.textBoxID;

            this.textBoxID.Select(this.textBoxID.Text.Length, 0);
        }
        private void textBoxPassword_GotFocus(object sender, EventArgs e)
        {
            // Automatic Logout Reset
            this.ParentForm.ChildFormMainDisplay.Part11AutomaticLogoutReset();

            this.smartKeyboard.TargetInputObject = this.textBoxPassword;

            this.textBoxPassword.Select(this.textBoxPassword.Text.Length, 0);
        }

        private void smartKeyboard_OnXKeyClick(object sender, EventArgs e)
        {
            this.smartKeyboard.Show();
        }

        private void smartKeyboard_Click(object sender, EventArgs e)
        {
            // Automatic Logout Reset
            this.ParentForm.ChildFormMainDisplay.Part11AutomaticLogoutReset();
        }
        #endregion

        private void buttonAdmin_Click(object sender, EventArgs e)
        {
            this.textBoxID.Text = "admin00";
            this.textBoxPassword.Text = "admin12!";
        }

        private void buttonIntech_Click(object sender, EventArgs e)
        {
            this.textBoxID.Text = "Intech";
            this.textBoxPassword.Text = "I20090810!";
        }
    }
}