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.DataHistoryProvider;
using C4IT.FASD.Licensing;

using static C4IT.Logging.cLogManager;
using System.Collections.ObjectModel;

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

        private async void ctrlMainFunction_Load(object sender, EventArgs e)
        {
            if (Program.mainForm == null)
                return;

            Program.mainForm.RemoveAllTabPages(Program.mainForm.tabPageMain);

            if (!Program.mainForm.CollectMode)
                return;

            MethodBase CM = null; if (cLogManager.DefaultLogger.IsDebug) { CM = MethodBase.GetCurrentMethod(); LogMethodBegin(CM); }
            try
            {
                Cursor = Cursors.WaitCursor;
                Program.Collector = null;

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

                buttonLoad.Visible = false;
                buttonCheckDatabase.Visible = false;
                buttonValidateAgentDb.Visible = false;
               

                var diff = ctrlProtocolBox1.Top - buttonLoad.Top;
                ctrlProtocolBox1.Top = buttonLoad.Top;
                ctrlProtocolBox1.Height += diff;
                ctrlProtocolBox1.ClearMessages();

                cF4SDLicense.CheckLicense(null, null);
                var lstLicenseLog = cF4SDLicense.LogLicenseState();
                foreach (var _s in lstLicenseLog)
                    ctrlProtocolBox1.ProcessMessage(_s);
                ctrlProtocolBox1.ProcessMessage("");
                if (!cF4SDLicense.Instance.IsValid)
                    return;

                var Collector = new cDataHistoryCollector(autoConnectionCheck: false, _requestInfo, 1);
                Collector.ProcessUiMessage += ctrlProtocolBox1.ProcessMessage;

                var IsLoaded = await Collector.LoadConfigurationAsync(true, false, CancellationToken.None, _requestInfo, 1);
                if (!IsLoaded)
                    return;

                Collector.ValidateClientConfiguration();

                var tabs = Program.mainForm.tabControlMain.TabPages.Cast<TabPage>().ToList();
                tabs.Remove(Program.mainForm.tabPageMain);
                foreach (var _entry in tabs)
                    Program.mainForm.tabControlMain.TabPages.Remove(_entry);

                var IsOk = await Collector.ValidateHistoryDatabasesAsync(false, CancellationToken.None, _requestInfo, 1);
                if (!IsOk)
                    return;

                await Task.Delay(1000);

                await Collector.ValidateF4SDAnalyticsDBAsync(_requestInfo, 1, CancellationToken.None);
                await Collector.UpdateF4SDAnalyticsConfigInfosAsync(_requestInfo, 1, CancellationToken.None);

                if (DateTime.Now.TimeOfDay >= TimeSpan.FromHours(22) || DateTime.Now.TimeOfDay < TimeSpan.FromHours(3))
                {
                    await Collector.ValidateAgentDbUpdates(_requestInfo, 1, CancellationToken.None);
                }

                if (Collector.F4sdAgent != null)
                {
                    await Collector.F4sdAgent.DoScanAsync(false, false, _requestInfo, 1, CancellationToken.None);
                    await Task.Delay(1000);
                }


                if (Collector.ActiveDirectory != null && await Collector.ActiveDirectory.DoScanAsync(false, false, _requestInfo, 1, CancellationToken.None))
                {
                    await Task.Delay(1000);
                    await Collector.F4sdAgent.DoScanAsync(true, false, _requestInfo, 1, CancellationToken.None);
                }
                await Task.Delay(1000);

                if (Collector.NxqlCollector != null)
                {
                    await Collector.NxqlCollector.DoScanAsync(false, false, _requestInfo, 1, CancellationToken.None);
                    await Task.Delay(1000);
                }

                if (Collector.M42WpmCollector != null)
                {
                    await Collector.M42WpmCollector.DoScanAsync(false, false, _requestInfo, 1, CancellationToken.None);
                    await Task.Delay(1000);
                }
                if (Collector.CitrixCollector != null)
                {
                    await Collector.CitrixCollector.DoScanAsync(false, false, _requestInfo, 1, CancellationToken.None);
                    await Task.Delay(1000);
                }
                await Collector.DoCleanup(false, _requestInfo, 1, CancellationToken.None);

            }
            catch (Exception E)
            {
                LogException(E);
            }
            finally
            {
                ctrlProtocolBox1.ProcessMessage("");

                await Task.Delay(10000);

                Cursor = Cursors.Default;
                if (CM != null) LogMethodEnd(CM);

                Program.mainForm.Close();
            }
        }

        private async void buttonLoad_Click(object sender, EventArgs e)
        {
            MethodBase CM = null; if (cLogManager.DefaultLogger.IsDebug) { CM = MethodBase.GetCurrentMethod(); LogMethodBegin(CM); }
            try
            {
                Cursor = Cursors.WaitCursor;
                Program.Collector = null;

                ctrlProtocolBox1.ClearMessages();
                buttonLoad.Enabled = false;
                buttonCheckDatabase.Enabled = false;

                Program.mainForm.DisableAllTabPages(this);

                cF4SDLicense.CheckLicense(null, null);
                var lstLicenseLog = cF4SDLicense.LogLicenseState();
                foreach (var _s in lstLicenseLog)
                    ctrlProtocolBox1.ProcessMessage(_s);
                ctrlProtocolBox1.ProcessMessage("");

                if (cF4SDLicense.Instance?.IsValid != true)
                    return;

                var Collector = new cDataHistoryCollector(autoConnectionCheck: false, null, 0);
                Collector.ProcessUiMessage += ctrlProtocolBox1.ProcessMessage;

                var _requestInfo = new cF4sdWebRequestInfo("buttonLoad_Click", null);
                var IsLoaded = await Collector.LoadConfigurationAsync(true, true, CancellationToken.None, null, 0);

                if (IsLoaded)
                {
                    ctrlProtocolBox1.ProcessMessage("");

                    Collector.ValidateClientConfiguration();

                    buttonCheckDatabase.Enabled = true;
                    Program.Collector = Collector;
                }
            }
            catch (Exception E)
            {
                LogException(E);
            }
            finally
            {
                ctrlProtocolBox1.ProcessMessage("");
                buttonLoad.Enabled = true;
                Cursor = Cursors.Default;
                if (CM != null) LogMethodEnd(CM);
            }

        }

        private async void buttonCheckDatabase_Click(object sender, EventArgs e)
        {
            if (Program.Collector == null)
                return;

            MethodBase CM = null; if (cLogManager.DefaultLogger.IsDebug) { CM = MethodBase.GetCurrentMethod(); LogMethodBegin(CM); }
            try
            {
                Cursor = Cursors.WaitCursor;
                this.Enabled = false;

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

                var _requestInfo = new cF4sdWebRequestInfo("buttonCheckDatabase_Click", null);
                var IsOk = await Program.Collector.ValidateHistoryDatabasesAsync(false, CancellationToken.None, _requestInfo, 0);

                if (IsOk)
                {
                    await Program.Collector.ValidateF4SDAnalyticsDBAsync(_requestInfo, 1, CancellationToken.None,true);
                    await Program.Collector.UpdateF4SDAnalyticsConfigInfosAsync(_requestInfo, 1, CancellationToken.None);

                    buttonValidateAgentDb.Enabled = true;

                    Program.mainForm.RemoveAllTabPages(Program.mainForm.tabPageMain);

                    Program.mainForm.tabControlMain.TabPages.Add(Program.mainForm.tabPageAgent);

                    Program.mainForm.tabControlMain.TabPages.Add(Program.mainForm.tabPageActiveDirectory);

                    Program.mainForm.tabControlMain.TabPages.Add(Program.mainForm.tabPageCleanup);

                    Program.mainForm.tabControlMain.TabPages.Add(Program.mainForm.tabPageTest);

                    if (Program.Collector.InfrastructureConfig.F4SDAnalyticsDB != null)
                        Program.mainForm.tabControlMain.TabPages.Add(Program.mainForm.tabPageF4SDAnalytics);

                    if (Program.Collector.CitrixCollector != null && Program.Collector.InfrastructureConfig.Citrix.Systems != null)
                        Program.mainForm.tabControlMain.TabPages.Add(Program.mainForm.tabPageCitrix);

                    if (Program.Collector.NxqlCollector != null && !Program.mainForm.tabControlMain.TabPages.Contains(Program.mainForm.tabPageNexthink))
                        Program.mainForm.tabControlMain.TabPages.Insert(3, Program.mainForm.tabPageNexthink);

                    if (Program.Collector.M42WpmCollector != null && !Program.mainForm.tabControlMain.TabPages.Contains(Program.mainForm.tabPageM42WPM))
                        Program.mainForm.tabControlMain.TabPages.Insert(3, Program.mainForm.tabPageM42WPM);

                    Program.mainForm.EnableAllTabPages();

                    

                }
            }
            catch (Exception E)
            {
                LogException(E);
            }
            finally
            {
                ctrlProtocolBox1.ProcessMessage("");
                this.Enabled = true;
                Cursor = Cursors.Default;
                if (CM != null) LogMethodEnd(CM);
            }


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

                Cursor = Cursors.WaitCursor;
                this.Enabled = false;
                Program.mainForm.DisableAllTabPages(this);

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

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

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