using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Net;
using System.Net.Sockets;
using Application = System.Windows.Forms.Application;
using AR;

namespace UniMarc
{
    public partial class login : Form
    {
        Helper_DB db = new Helper_DB();
        IP ip = new IP();
        public login()
        {
            InitializeComponent();
        }

        private void login_Load(object sender, EventArgs e)
        {
            lbl_IP.Text = String.Format("{0}", ip.GetIP());
            lbl_Version.Text = string.Format("Ver.{0}", ip.VersionInfo());

            this.ActiveControl = ID_text;

            if (CreateFile()) {
                chk_Save.Checked = true;
                ReadFile();
            }
            db.DBcon();
            MakeVersionData();
        }

        private void MakeVersionData()
        {
            string[] Res_Ary = db.DB_Send_CMD_Search("SELECT `version`, `content` FROM `Update` ORDER BY `idx` DESC;").Split('|');
            string[] Grid = { "", "" };
            for (int a = 0; a < Res_Ary.Length; a++)
            {
                if (a % 2 == 0) Grid[0] = "Ver." + Res_Ary[a];
                if (a % 2 == 1) {
                    Grid[1]=Res_Ary[a];
                    dataGridView1.Rows.Add(Grid);
                }
            }
            richTextBox1.Text = dataGridView1.Rows[0].Cells["Content"].Value.ToString();
        }

        private void Login_Click(object sender, EventArgs e)
        {
            db.DBcon();
            string cmd = db.DB_Search("User_Data", "id", ID_text.Text);
            string db_res = db.DB_Send_CMD_Search(cmd);
            string[] result = db_res.Split('|');
            ((Main)(this.Owner)).User_Name = ID_text.Text;
            if (db_res == "")
            {
                UTIL.MsgE("아이디 혹은 비밀번호가 정확하지않습니다.");
                return;
            }

            if (ID_text.Text == result[1])
            {
                if (PW_text.Text == result[2])
                {
                    if (chk_Save.Checked)
                        if (!CreateFile())
                            WriteFile();
                    if (!CheckIP(lbl_IP.Text, result[4]))
                    {
                        UTIL.MsgE("허용된 아이피가 아닙니다!");
                        return;
                    }
                    ((Main)(this.Owner)).IPText.Text = string.Format("접속 아이피 : {0}", lbl_IP.Text);
                    Helper_DB.ExcuteNonQuery(
                        string.Format("UPDATE `User_Data` SET `lastIP` = \"{0}\", `lastDate` = \"{2}\" WHERE `ID` = \"{1}\"",
                        lbl_IP.Text, ID_text.Text, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"))
                        );
                    this.DialogResult = DialogResult.OK;
                    this.Close();
                }
                else
                {
                    UTIL.MsgE("아이디 혹은 비밀번호가 정확하지않습니다.");
                }
            }
            else
            {
                UTIL.MsgE("아이디 혹은 비밀번호가 정확하지않습니다.");
            }
        }
        #region CheckIP

        /// <summary>
        /// 해당 ID와 IP대조
        /// </summary>
        /// <param name="IP">현재 IP의 아이피</param>
        /// <returns></returns>
        public bool CheckIP(string IP, string compName)
        {
            string cmd = String.Format("SELECT `{0}` FROM {1} WHERE `{2}` = \"{3}\"", "IP", "Comp", "comp_name", compName);
            string res = db.DB_Send_CMD_Search(cmd);
            string[] ary = res.Split('|');

            foreach (string item in ary)
            {
                if (item == IP)
                    return true;

                if (item == "ALL")
                    return true;
            }

            return false;
        }
        #endregion

        #region AutoLogin
        /// <summary>
        /// 파일이 있는지 확인하고 없으면 생성
        /// </summary>
        /// <returns>생성시 false</returns>
        private bool CreateFile()
        {
            string path = Application.StartupPath + "\\AutoLogin.txt";
            
            if (!File.Exists(path))
            {
                return false;
            }
            return true;
        }

        private void WriteFile()
        {
            string path = Application.StartupPath + "\\AutoLogin.txt";
            string contents = string.Format("ID={0}\nPW={1}", ID_text.Text, PW_text.Text);

            File.WriteAllText(path, contents);

            // StreamWriter writer;
            // writer = File.AppendText(path);
            // writer.Write(string.Format("ID={0}\nPW={1}", ID_text.Text, PW_text.Text));
            // writer.Close();
        }

        private void ReadFile()
        {
            string LoginData = File.ReadAllText(Application.StartupPath + "\\AutoLogin.txt");
            string[] Ary = LoginData.Split('\n');
            
            if (Ary.Length < 1)
                return;

            //System.Text.RegularExpressions.Regex.Replace()
            Ary[0] = Ary[0].Replace("ID=", "");
            ID_text.Text = System.Text.RegularExpressions.Regex.Replace(Ary[0], @"[^a-zA-Z0-9]", "");
            PW_text.Text = Ary[1].Replace("PW=", "");
        }
        #endregion

        private void Btn_Close_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void ID_text_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter) { this.ActiveControl = PW_text; }
            if (e.KeyCode == Keys.Escape) { this.Close(); }
        }

        private void PW_text_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter) { Login_Click(null, null); }
            if (e.KeyCode == Keys.Escape) { this.Close(); }
        }

        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0) return;

            richTextBox1.Text = dataGridView1.Rows[e.RowIndex].Cells["Content"].Value.ToString();
        }
    }
}
