using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

using C4IT.Logging;
using C4IT.XML;
using C4IT.FASD.Base;
using C4IT.DataHistoryProvider;

using static C4IT.Logging.cLogManager;

namespace C4IT_DataHistoryProvider_Test
{
    public partial class ctrlM42Wpm : UserControl
    {
        public ctrlM42Wpm()
        {
            InitializeComponent();
        }

        private async void ctrlM42Wpm_Load(object sender, EventArgs e)
        {
            MethodBase CM = null; if (cLogManager.DefaultLogger.IsDebug) { CM = MethodBase.GetCurrentMethod(); LogMethodBegin(CM); }

            if (Program.Collector == null)
                return;

            try
            {
                Cursor = Cursors.WaitCursor;

                ctrlProtocolBox1.ClearMessages();

                Program.mainForm.DisableAllTabPages(this);

                Program.Collector.CleanupUiMessageHandler();
                Program.Collector.ProcessUiMessage += ctrlProtocolBox1.ProcessMessage;

                var _requestInfo = new cF4sdWebRequestInfo("ctrlM42Wpm_Load", null);

                if (Program.UserList == null)
                    Program.UserList = await Program.Collector.GetInfoClassListTest(C4IT.FASD.Base.enumFasdInformationClass.User, true, _requestInfo, 1, CancellationToken.None);

                comboBoxUserSelect.Items.AddRange(Program.UserList.ToArray());

                ctrlProtocolBox1.ProcessMessage("");

                await checkScanTimesAsync(_requestInfo, 1);
            }
            catch (Exception E)
            {
                LogException(E);
            }
            finally
            {
                ctrlProtocolBox1.ProcessMessage("");
                Program.mainForm.EnableAllTabPages();
                Cursor = Cursors.Default;
                if (CM != null) LogMethodEnd(CM);
            }
        }

        private async void buttonCheckConnection_Click(object sender, EventArgs e)
        {
            MethodBase CM = null; if (cLogManager.DefaultLogger.IsDebug) { CM = MethodBase.GetCurrentMethod(); LogMethodBegin(CM); }

            if (Program.Collector == null)
                return;

            try
            {
                Cursor = Cursors.WaitCursor;

                ctrlProtocolBox1.ClearMessages();
                buttonCheckConnection.Enabled = false;

                Program.mainForm.DisableAllTabPages(this);

                Program.Collector.CleanupUiMessageHandler();
                Program.Collector.ProcessUiMessage += ctrlProtocolBox1.ProcessMessage;

                var res = await Program.Collector.M42WpmCollector.ValidateConnectionAsync(true, CancellationToken.None);

                buttonGetUserTickes.Enabled = res;
            }
            catch (Exception E)
            {
                LogException(E);
            }
            finally
            {
                ctrlProtocolBox1.ProcessMessage("");
                Program.mainForm.EnableAllTabPages();
                buttonCheckConnection.Enabled = true;
                Cursor = Cursors.Default;
                if (CM != null) LogMethodEnd(CM);
            }


        }

        private class TicketEntry
        {
            public string Name;
            public Guid Id;

            public override string ToString()
            {
                return Name;
            }
        }

        private async void buttonGetUserTickes_Click(object sender, EventArgs e)
        {
            MethodBase CM = null; if (cLogManager.DefaultLogger.IsDebug) { CM = MethodBase.GetCurrentMethod(); LogMethodBegin(CM); }
            try
            {
                comboBoxTicket.Enabled = false;
                comboBoxTicket.Items.Clear();
                comboBoxTicket.SelectedItem = null;
                if (comboBoxUserSelect.SelectedItem == null || !(comboBoxUserSelect.SelectedItem is cDataHistoryInfoClassListEntry info))
                    return;

                var search = new List<cF4sdIdentityEntry>()
                {
                    new cF4sdIdentityEntry()
                    {
                        Class = enumFasdInformationClass.User,
                        Id = info.id,
                    }
                };

                ctrlProtocolBox1.ProcessMessage("");

                var found = false;
                var userinfo = await Program.Collector.getConntectorIds(search, CancellationToken.None, null, 0);
                if (userinfo != null && userinfo.TryGetValue(enumFasdInformationClass.User, out var userids))
                {
                    if (userids.sid != null)
                    {
                        var TicketList = await Program.Collector.M42WpmCollector.getTicketUsage(new List<cF4sdConnectorIds> { userids }, CancellationToken.None, null, 0);
                        var Tickets = new List<TicketEntry>();
                        if (TicketList != null && TicketList.Count > 0)
                        {
                            found = true;
                            ctrlProtocolBox1.ProcessMessage($"{TicketList.Count} tickets found for user '{info.Name}':");
                            foreach (var Entry in TicketList)
                            {
                                Tickets.Add(new TicketEntry() { Name = Entry.Name, Id = Entry.id });

                                ctrlProtocolBox1.ProcessMessage("");
                                ctrlProtocolBox1.ProcessMessage($"  {Entry.Name}:");

                                foreach (var Entry2 in Entry.Infos)
                                {
                                    ctrlProtocolBox1.ProcessMessage($"    {Entry2.Key}: {Entry2.Value}");
                                }
                            }

                        }

                        if (Tickets.Count > 0)
                        {
                            comboBoxTicket.Items.AddRange(Tickets.ToArray());
                            comboBoxTicket.Enabled = true;
                        }
                    }
                }
                if (!found)
                    ctrlProtocolBox1.ProcessMessage($"no tickets found for user '{info.Name}'");
            }
            catch (Exception E)
            {
                LogException(E);
            }
            finally
            {
                if (CM != null) LogMethodEnd(CM);
            }
        }

        private void comboBoxTicket_SelectedValueChanged(object sender, EventArgs e)
        {
            buttonUpdateSolution.Enabled = comboBoxTicket.SelectedItem != null;
        }

        private async void buttonUpdateSolution_Click(object sender, EventArgs e)
        {
            MethodBase CM = null; if (cLogManager.DefaultLogger.IsDebug) { CM = MethodBase.GetCurrentMethod(); LogMethodBegin(CM); }
            try
            {
                if (!(comboBoxTicket.SelectedItem is TicketEntry _ticket))
                    return;

                var _update = new cF4SDWriteParameters()
                {
                    TableName = cDataHistoryCollectorM42Wpm.constTableNameTicketDetails,
                    id = _ticket.Id,
                    Values = new Dictionary<string, object>(1) { { "SolutionHtml", "Closed for F4SD testing purposes." } }
                };

                var _res = await Program.Collector.WritePropertyAsync(_update, null, CancellationToken.None);
            }
            catch (Exception E)
            {
                LogException(E);
            }
            finally
            {
                if (CM != null) LogMethodEnd(CM);
            }
        }

        private async Task checkScanTimesAsync(cF4sdWebRequestInfo requestInfo, int LogDeep)
        {
            MethodBase CM = null; if (cLogManager.DefaultLogger.IsDebug) { CM = MethodBase.GetCurrentMethod(); LogMethodBegin(CM); }
            if (cPerformanceLogger.IsActive && requestInfo != null) { if (CM == null) CM = MethodBase.GetCurrentMethod(); cPerformanceLogger.LogPerformanceStart(LogDeep, CM, requestInfo.id, requestInfo.created); }
            var _startTime = DateTime.UtcNow;

            try
            {
                var Col = Color.Transparent;
                textBoxScanLast.Text = "";
                textBoxScanNext.Text = "";

                if (Program.Collector.M42WpmCollector != null)
                {
                    var scanInfo = await Program.Collector.M42WpmCollector.GetScanTimeInfoAsync(requestInfo, LogDeep + 1, CancellationToken.None);

                    if (scanInfo?.NextScan is DateTime nextScan)
                    {
                        textBoxScanNext.Text = nextScan.ToLocalTime().ToString();
                        if (scanInfo?.LastScan is DateTime lastScan)
                        {
                            textBoxScanLast.Text = lastScan.ToLocalTime().ToString();
                            if (nextScan >= lastScan)
                                Col = Color.Red;
                            else
                                Col = Color.Green;
                        }
                        else
                            Col = Color.Red;
                    }
                    else
                    {
                        Col = Color.Red;
                        if (scanInfo?.LastScan is DateTime lastScan)
                            textBoxScanLast.Text = lastScan.ToLocalTime().ToString();
                    }
                }

                panelScanNext.BackColor = Col;

            }
            catch (Exception E)
            {
                LogException(E);
            }
            finally
            {
                if (cPerformanceLogger.IsActive && requestInfo != null) { cPerformanceLogger.LogPerformanceEnd(LogDeep, CM, requestInfo.id, requestInfo.created, _startTime); }
                if (CM != null) LogMethodEnd(CM);
            }
        }

        private async void buttonScanM42_Click(object sender, EventArgs e)
        {
            MethodBase CM = null; if (cLogManager.DefaultLogger.IsDebug) { CM = MethodBase.GetCurrentMethod(); LogMethodBegin(CM); }

            if (Program.Collector == null)
                return;

            try
            {
                Cursor = Cursors.WaitCursor;

                ctrlProtocolBox1.ClearMessages();
                buttonScanM42.Enabled = false;

                Program.mainForm.DisableAllTabPages(this);

                Program.Collector.CleanupUiMessageHandler();
                Program.Collector.ProcessUiMessage += ctrlProtocolBox1.ProcessMessage;
                var _requestInfo = new cF4sdWebRequestInfo("DoScanM42Wpm", null);
                await Program.Collector.M42WpmCollector.DoScanAsync(true, true, _requestInfo, 1, CancellationToken.None);

                await checkScanTimesAsync(_requestInfo, 1);
            }
            catch (Exception E)
            {
                LogException(E);
            }
            finally
            {
                ctrlProtocolBox1.ProcessMessage("");
                Program.mainForm.EnableAllTabPages();
                buttonScanM42.Enabled = true;
                Cursor = Cursors.Default;
                if (CM != null) LogMethodEnd(CM);
            }

        }
    }
}
