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 static C4IT.Logging.cLogManager;
using C4IT.MsGraph;
using Newtonsoft.Json.Linq;
using System.Collections.ObjectModel;

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

        private async void ctrlActiveDirectory_Load(object sender, EventArgs e)
        {
            panelScanNext.Height = textBoxScanNext.Height;
            panelScanNext.Top = textBoxScanNext.Top;

            if (Program.Collector?.InfrastructureConfig?.AzureTenants != null && Program.Collector?.InfrastructureConfig?.AzureTenants.Count > 0)
            {
                buttonScanAzureAd.Visible = true;                

            }

            if (Program.Collector?.InfrastructureConfig?.AzureTenants != null && Program.Collector?.InfrastructureConfig?.AzureTenants.Count > 0)
            {
                buttonScanAzureAd.Visible = true;                
               
            }

            var _requestInfo = new cF4sdWebRequestInfo("ctrlActiveDirectory_Load", null);
            await checkScanTimesAsync(_requestInfo,1);
        }

        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?.ActiveDirectory != null)
                {
                    var scanInfo = await Program.Collector.ActiveDirectory.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 Task DoScan(bool Rescan, cF4sdWebRequestInfo requestInfo, int LogDeep)
        {
            if (Program.Collector == null || Program.Collector.ActiveDirectory == null)
                return;

            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
            {
                Cursor = Cursors.WaitCursor;

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

                Program.mainForm.DisableAllTabPages(this);

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

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

                await Program.Collector.ActiveDirectory.DoScanAsync(true, Rescan, _requestInfo, 1, CancellationToken.None);

                await checkScanTimesAsync(requestInfo, LogDeep+1);
            }
            catch (Exception E)
            {
                LogException(E);
            }
            finally
            {
                ctrlProtocolBox1.ProcessMessage("");
                Program.mainForm.EnableAllTabPages();
                buttonScanAD.Enabled = true;
                Cursor = Cursors.Default;

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

        }

        private async void buttonRescan_Click(object sender, EventArgs e)
        {
            var _requestInfo = new cF4sdWebRequestInfo("buttonRescan_Click", null);
            await DoScan(true, _requestInfo, 1);
            DoDeviceScanAzure(sender, e);
        }

        private async void buttonScanAD_Click(object sender, EventArgs e)
        {
            var _requestInfo = new cF4sdWebRequestInfo("buttonScanAD_Click", null);
            await DoScan(false, _requestInfo, 1);
            DoDeviceScanAzure(sender,e);

        }

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

            if (Program.Collector == null || Program.Collector.ActiveDirectory == null)
                return;

            try
            {
                Cursor = Cursors.WaitCursor;

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

                Program.mainForm.DisableAllTabPages(this);

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

                var _requestInfo = new cF4sdWebRequestInfo("buttonScanAzureAd_Click", null);
                await Program.Collector.ActiveDirectory.DoAzureScanAsync(_requestInfo, 1, CancellationToken.None);
                DoDeviceScanAzure(sender, e);
            }
            catch (Exception E)
            {
                LogException(E);
            }
            finally
            {
                ctrlProtocolBox1.ProcessMessage("");
                Program.mainForm.EnableAllTabPages();
                buttonScanAD.Enabled = true;
                Cursor = Cursors.Default;
                if (CM != null) LogMethodEnd(CM);
            }
        }
       
        private async void DoDeviceScanAzure(object sender, EventArgs e)
        {
            MethodBase CM = null; if (cLogManager.DefaultLogger.IsDebug) { CM = MethodBase.GetCurrentMethod(); LogMethodBegin(CM); }

            if (Program.Collector == null || Program.Collector.ActiveDirectory == null)
                return;

            try
            {
                Cursor = Cursors.WaitCursor;

                Program.mainForm.DisableAllTabPages(this);

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

                var _requestInfo = new cF4sdWebRequestInfo("DoDeviceScanAzure", null);
                await Program.Collector.ActiveDirectory.DoDeviceScanAzureAsync(_requestInfo, 1, CancellationToken.None);
            }
            catch (Exception E)
            {
                LogException(E);
            }
            finally
            {
                ctrlProtocolBox1.ProcessMessage("");
                Program.mainForm.EnableAllTabPages();
                DoScanIntune(sender,e);
                Cursor = Cursors.Default;
                if (CM != null) LogMethodEnd(CM);
            }
        }

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

            if (Program.Collector == null || Program.Collector.ActiveDirectory == null)
                return;

            try
            {
                Cursor = Cursors.WaitCursor;
                
                Program.mainForm.DisableAllTabPages(this);

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

                var _requestInfo = new cF4sdWebRequestInfo("DoScanIntune", null);
                await Program.Collector.ActiveDirectory.DoScanIntuneAsync(null, 1, CancellationToken.None);
            }
            catch (Exception E)
            {
                LogException(E);
            }
            finally
            {
                Program.mainForm.EnableAllTabPages();               
                Cursor = Cursors.Default;
                if (CM != null) LogMethodEnd(CM);
            }
        }       

    }
}
