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;

namespace JtkManagerClient {
    public partial class GuestListForm : Form {
        //public delegate string[] GetGuestsDelegate();
        //private GetGuestsDelegate GetGuests;
        public GuestListForm() {
            InitializeComponent();
            UpdateGuestList();
        }

        private async void UpdateGuestList() {
            try {
                var response = await Program.GetPostResponseAsync(new { work = "get_guest_list" });
                guestListView.Items.Clear();
                if (response.TryGetValue("list", out var tknList)) {
                    foreach (var tkn in tknList) {
                        var guestId = tkn["guest_id"]?.ToString();
                        var cash = "￦"+tkn["cash"]?.ToObject<double>().ToString("N0");
                        var isLoggedIn = tkn["is_logged_in"]?.ToObject<bool>() ?? false;
                        guestListView.Items.Add(new ListViewItem(new string[] { guestId, cash, isLoggedIn ? "O" : "-" }));
                    }
                }
            } catch {
                MessageBox.Show("갱신하지 못했습니다.", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private async void addButton_Click(object sender, EventArgs e) {
            try {
                var form = new GuestAddForm();
                form.ShowDialog();
                if (form.DialogResult == DialogResult.OK) {
                    var response = await Program.GetPostResponseAsync(new { work = "guest_add", cash = form.Cash });
                    var result = response["result"].ToString();
                    if (result == "ok") {
                        MessageBox.Show($"{response["guest_id"]} 추가되었습니다.", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        UpdateGuestList();
                    } else {
                        throw new Exception();
                    }
                }
            } catch {
                MessageBox.Show("추가하지 못했습니다.", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private async void chargeButton_Click(object sender, EventArgs e) {
            try {
                var form = new GuestChargeForm();
                form.ShowDialog();
                if (form.DialogResult == DialogResult.OK) {
                    int succeed = 0;
                    foreach (ListViewItem item in guestListView.SelectedItems) {
                        var response = await Program.GetPostResponseAsync(new { guest_id = item.Text, work = "guest_cash_charge", cash_charging = form.Cash });
                        var result = response["result"].ToString();
                        if (result == "ok") {
                            succeed++;
                        }
                    }

                    if (guestListView.SelectedItems.Count == 1) {
                        if (succeed == 1) {
                            MessageBox.Show($"{guestListView.SelectedItems[0].Text}에 {form.Cash:N0}원이 충전되었습니다.", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        } else {
                            throw new Exception();
                        }
                    } else {
                        if (succeed != guestListView.SelectedItems.Count) {
                            MessageBox.Show($"{form.Cash:N0}원이 충전되었습니다. (성공:{succeed:N0}, 실패:{guestListView.SelectedItems.Count-succeed:N0})", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        } else {
                            MessageBox.Show($"{form.Cash:N0}원이 충전되었습니다.", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                    }
                    UpdateGuestList();
                }
            } catch {
                MessageBox.Show("충전하지 못했습니다.", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private async void deleteButton_Click(object sender, EventArgs e) {
            if (MessageBox.Show("삭제하시겠습니까?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.No) {
                return;
            }
            try {
                int succeed = 0;
                foreach (ListViewItem item in guestListView.SelectedItems) {
                    var response = await Program.GetPostResponseAsync(new { guest_id = item.Text, work = "guest_delete" });
                    var result = response["result"].ToString();
                    if (result == "ok") {
                        succeed++;
                    }
                }

                if (guestListView.SelectedItems.Count == 1) {
                    if (succeed == 1) {
                        MessageBox.Show($"{guestListView.SelectedItems[0].Text} 삭제되었습니다.", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    } else {
                        throw new Exception();
                    }
                } else {
                    if (succeed != guestListView.SelectedItems.Count) {
                        MessageBox.Show($"삭제되었습니다. (성공:{succeed:N0}, 실패:{guestListView.SelectedItems.Count - succeed:N0})", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    } else {
                        MessageBox.Show($"삭제되었습니다.", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
                UpdateGuestList();
            } catch {
                MessageBox.Show("삭제하지 못했습니다.", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void refreshButton_Click(object sender, EventArgs e) {
            UpdateGuestList();
        }

        private void guestListView_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e) {
            chargeButton.Enabled = deleteButton.Enabled = guestListView.SelectedItems.Count > 0;
        }

        private void GuestListForm_KeyDown(object sender, KeyEventArgs e) {
            if (e.KeyCode == Keys.Escape || ModifierKeys == Keys.Control && e.KeyCode == Keys.C) {
                Close();
            }
        }

        private void GuestListForm_Load(object sender, EventArgs e) {
            var scale = CreateGraphics().DpiX / 96f;
            foreach (ColumnHeader col in guestListView.Columns) {
                col.Width = (int)(col.Width * scale);
            }
        }
    }
}
