using System;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace Cheongbuk_MegaPark_Key_Management
{
    public partial class MainForm : Form
    {
        // 기본 Database
        private readonly DB _database = new DB();

        public MainForm()
        {
            InitializeComponent();
        }

        private void ClockTimer_Tick(object sender, EventArgs e)
        {
            ClockChanger();
        }

        private void ClockChanger()
        {
            Clock.Text = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            // Check DBFile
            if (!File.Exists(Setting.DbLocation))
            {
                MessageBox.Show("DATABASE 파일을 찾을수 없습니다.\r\n프로그램을 종료합니다.", "프로그램 에러", MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
                Application.Exit();
            }

            // Clock Init Setting
            Clock.Font = new Font(FontLibrary.Families[0], 30, FontStyle.Bold);
            //button_RentKey.Font = new Font(FontLibrary.Families[1], 10);
            ClockChanger();

            //Database Load
            _database.LoadData();

            //MainScreen Init Change
            ChangeMainScreenData();

            //ListView Init Setting
            listView_Profit.Items.Clear();
            listView_Rent.Items.Clear();
            foreach (var rentData in Setting.RentDatas) ListViewRentDataAdd(rentData);
            foreach (var profitData in Setting.ProfitDatas) ListViewProfitDataAdd(profitData);
        }

        private void ListViewRentDataAdd(RentData rentData)
        {
            var data = new string[3];
            data[0] = rentData.KeyCode.ToString();
            data[1] = Setting.CategoryDictionary[rentData.Category].CategoryName;
            data[2] = rentData.StartDateTime.ToString("yyyy/MM/dd HH:mm:ss");
            listView_Rent.Items.Add(new ListViewItem(data));
        }

        private void ListViewProfitDataAdd(ProfitData profitData)
        {
            var data = new string[5];
            data[0] = profitData.Id.ToString();
            data[1] = profitData.KeyCode.ToString();
            data[2] = Setting.CategoryDictionary[profitData.Category].CategoryName;
            data[3] = profitData.UseTime / 60 + "시간 " + profitData.UseTime % 60 + "분";
            data[4] = $"{profitData.ProfitAdd - profitData.ProfitDiscount:#,##0원}";
            listView_Profit.Items.Add(new ListViewItem(data));
        }

        // 메인 스크린 데이터 갱신
        private void ChangeMainScreenData()
        {
            int sumProfitAdd = Setting.ProfitDatas.Sum(x => x.ProfitAdd);
            int sumProfitDiscount = Setting.ProfitDatas.Sum(x => x.ProfitDiscount);

            label_AllKeyCount.Text = $"{Setting.RentDatas.Count + Setting.ProfitDatas.Count:#,##0}";
            label_NowKeyCount.Text = $"{Setting.RentDatas.Count:#,##0}";
            label_Profit.Text = (sumProfitAdd - sumProfitDiscount).ToMoney();
        }

        private void TextBox_KeyNumber_TextChanged(object sender, EventArgs e)
        {
            var value = Regex.Replace(textBox_KeyNumber.Text, "[^0-9]", "");
            if (value != textBox_KeyNumber.Text)
            {
                textBox_KeyNumber.Text = value;
                textBox_KeyNumber.SelectionStart = textBox_KeyNumber.Text.Length;
            }
        }

        private void TextBox_KeyNumber_Changer(object sender, EventArgs e)
        {
            int.TryParse(((Button)sender).Tag.ToString(), out var key);
            if (key > -1)
            {
                if (key != 0 || textBox_KeyNumber.Text != string.Empty) textBox_KeyNumber.Text += key.ToString();
            }
            else
            {
                switch (key)
                {
                    case -1:
                        {
                            if (textBox_KeyNumber.Text.Length != 0)
                                textBox_KeyNumber.Text =
                                    textBox_KeyNumber.Text.Substring(0, textBox_KeyNumber.Text.Length - 1);
                            break;
                        }

                    case -2:
                        textBox_KeyNumber.Text = string.Empty;
                        break;
                }
            }

            textBox_KeyNumber.Focus();
            textBox_KeyNumber.SelectionStart = textBox_KeyNumber.Text.Length;
        }

        private void Button_RentKey_Click(object sender, EventArgs e)
        {
            RentReturnProcess();
            textBox_KeyNumber.Focus();
        }

        private void TextBox_KeyNumber_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar != 13) return;
            RentReturnProcess();
            textBox_KeyNumber.Focus();
        }

        private void RentReturnProcess()
        {
            int.TryParse(textBox_KeyNumber.Text, out var key);
            if (key == 0) return;

            var tempRentData = (from rentData in Setting.RentDatas where rentData.KeyCode == key select rentData)
                .FirstOrDefault();

            // 대여 프로세스
            if (tempRentData.KeyCode == 0)
            {
                var rentKey = new RentKey { KeyCode = key };
                if (DialogResult.Yes == rentKey.ShowDialog())
                {
                    var returnData = rentKey.ReturnData;

                    Setting.RentDatas.Add(returnData);
                    ListViewRentDataAdd(returnData);
                    _database.InsertRent(returnData);
                    textBox_KeyNumber.Text = string.Empty;
                }
            }
            // 반납프로세스
            else
            {
                var returnKey = new ReturnKey { Data = tempRentData };

                if (DialogResult.Yes == returnKey.ShowDialog())
                {
                    var returnData = returnKey.ReturnData;

                    var rD = new RentData();
                    foreach (var rentData in Setting.RentDatas)
                        if (rentData.KeyCode == returnData.KeyCode)
                            rD = rentData;

                    Setting.RentDatas.Remove(rD);

                    foreach (ListViewItem listViewItem in listView_Rent.Items)
                        if (listViewItem.SubItems[0].Text == returnData.KeyCode.ToString())
                            listView_Rent.Items.Remove(listViewItem);

                    returnData.Id = _database.ReturnRent(returnData);
                    Setting.ProfitDatas.Add(returnData);
                    ListViewProfitDataAdd(returnData);
                }

                textBox_KeyNumber.Text = string.Empty;
            }

            ChangeMainScreenData();
        }

        private void ListView_Profit_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button.Equals(MouseButtons.Right))
            {
                int.TryParse(listView_Profit.SelectedItems[0].Text, out int value);

                if (DialogResult.Yes == MessageBox.Show("정말 선택된 데이터를 삭제하시겠습니까?", "삭제 확인",
                        MessageBoxButtons.YesNo,
                        MessageBoxIcon.Question))
                {
                    ProfitData pf = new ProfitData();
                    foreach (var profitData in Setting.ProfitDatas.Where(profitData => profitData.Id == value))
                    {
                        pf = profitData;
                    }
                    Setting.ProfitDatas.Remove(pf);
                    _database.DeleteProfitData(value);
                    listView_Profit.Items.RemoveAt(listView_Profit.SelectedItems[0].Index);
                    ChangeMainScreenData();
                }
            }
        }

        private void ListView_Rent_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            int.TryParse(listView_Rent.SelectedItems[0].Text, out int value);
            RentData rD = new RentData();
            foreach (var rentData in Setting.RentDatas.Where(x => x.KeyCode == value))
            {
                rD = rentData;
            }
            RentKeyInfo rentKeyInfo = new RentKeyInfo();
            rentKeyInfo.RentKeyData = rD;
            rentKeyInfo.ShowDialog();

            textBox_KeyNumber.Focus();
        }

        private void ListView_Profit_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            int.TryParse(listView_Profit.SelectedItems[0].Text, out int value);
            ProfitData pD = new ProfitData();
            foreach (var profitData in Setting.ProfitDatas.Where(x => x.Id == value))
            {
                pD = profitData;
            }
            ReturnKeyInfo returnKeyInfo = new ReturnKeyInfo();
            returnKeyInfo.ProfitDataInfo = pD;
            returnKeyInfo.ShowDialog();

            textBox_KeyNumber.Focus();
        }
    }
}