using Pilz.Updating.Administration.Discord;
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 Telerik.WinControls;
using Telerik.WinControls.UI;

namespace Pilz.Updating.Administration.GUI
{
    public partial class DiscordPostDialog : RadForm
    {
        // F i e l d s

        private readonly DiscordBot bot;
        private readonly UpdatePackageInfo package;

        // C o n s t r u c t o r

        public DiscordPostDialog(DiscordBot bot, UpdatePackageInfo package)
        {
            this.bot = bot;
            this.package = package;

            InitializeComponent();

            radTextBoxControl_ProgramName.Text = General.CurProject.DiscordBotConfig.DefaultAppName;
            radTextBox_Message.Text = General.CurProject.DiscordBotConfig.DefaultUpdateMessage;

            LoadBgrTree();
        }

        private void LoadBgrTree()
        {
            radTreeView_Channels.BeginUpdate();
            radTreeView_Channels.Nodes.Clear();

            foreach (var guild in bot.GetGuilds())
            {
                var nGuild = new RadTreeNode()
                {
                    Name = "g" + guild.Key,
                    Text = guild.Value,
                    Tag = guild.Key,
                    Expanded = true
                };

                foreach (var channel in bot.GetTextChannels(guild.Key).OrderBy((n) => n.Value))
                {
                    var nChannel = new RadTreeNode()
                    {
                        Name = "c" + channel.Key,
                        Text = "#" + channel.Value,
                        Tag = channel.Key
                    };

                    nGuild.Nodes.Add(nChannel);
                }

                radTreeView_Channels.Nodes.Add(nGuild);
            }

            radTreeView_Channels.EndUpdate();
        }

        private async void ButtonX_SendMsg_Click(object sender, EventArgs e)
        {
            try
            {
                var selNode = radTreeView_Channels.SelectedNode;
                ulong gID = (ulong)selNode.Parent.Tag;
                ulong cID = (ulong)selNode.Tag;
                var msg = radTextBox_Message.Text;

                await bot.SendUpdateNotification(package, gID, cID, radTextBoxControl_ProgramName.Text, msg, radCheckBox_AttachDescription.Checked, radCheckBoxPingAtEveryone.Checked);

                RadMessageBox.Show(this, "Nachricht erfolgreich gesendet.", string.Empty, MessageBoxButtons.OK, RadMessageIcon.Info);
                DialogResult = DialogResult.OK;
            }
            catch(Exception)
            {
                RadMessageBox.Show(this, "Fehler beim Senden der Nachricht.", string.Empty, MessageBoxButtons.OK, RadMessageIcon.Error);
            }            
        }
    }
}
