using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
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.DataHistoryProvider;
using C4IT.FASD.Base;
using C4IT.FASD.Licensing;
using C4IT.Logging;
using static C4IT.Logging.cLogManager;

namespace C4IT_DataHistoryProvider_Test
{
    public partial class ctrlF4SDAnalytics : UserControl
    {
        Guid SessionId;
        Guid Userid = new Guid("7003cfbf-2841-454e-a4c7-2cff2eb45b23");
        Guid CaseId;

        private System.Timers.Timer SessionCheck;
        private System.Timers.Timer CaseCheck;

        public ctrlF4SDAnalytics()
        {
            InitializeComponent();
        }

        private async void buttonCreateSession_Click(object sender, EventArgs e)
        {

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

                ctrlProtocolBox1.ClearMessages();
                btnCreateSession.Enabled = false;
                if (Program.Collector == null)
                    return;

                if (Program.Collector.F4SDAnalyticsValid)
                {
                    SessionId = Guid.NewGuid();
                    var userSessions = new cF4SDUserSessionParameters();
                    userSessions.SessionId = SessionId;
                    userSessions.UserId = Userid;
                    userSessions.SessionDate = DateTime.UtcNow;
                    Program.Collector.CleanupUiMessageHandler();
                    Program.Collector.ProcessUiMessage += ctrlProtocolBox1.ProcessMessage;
                    var _requestInfo = new cF4sdWebRequestInfo("buttonCreateSession_Click", null);
                    bool IsCreatet = await Program.Collector.CreateUserSessionAsync(userSessions, _requestInfo, 1, CancellationToken.None);

                    btnStartCase.Enabled = true;
                    btnCloseSession.Enabled = true;
                    grpBoxCase.Visible = true;
                    btnCloseCase.Enabled = false;
                    btnHoldCase.Enabled = false;
                    btnCancelCase.Enabled = false;
                }
            }
            catch (Exception E)
            {
                LogException(E);
            }
            finally
            {
                if (CM != null) LogMethodEnd(CM);
                Cursor = Cursors.Default;
            }


        }

        private async void buttonCloseSession_Click(object sender, EventArgs e)
        {

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

                //btnInsertSession.Enabled = false;
                if (Program.Collector == null)
                    return;

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

                if (Program.Collector.F4SDAnalyticsValid && SessionId != null)
                {
                    var userSessions = new cF4SDUserSessionParameters();
                    userSessions.SessionId = SessionId;
                    userSessions.SessionDate = DateTime.UtcNow;
                    bool IsLoaded = await Program.Collector.CloseUserSessionAsync(userSessions, _requestInfo, 1, CancellationToken.None);
                    btnCloseSession.Enabled = false;
                    btnCreateSession.Enabled = true;
                    grpBoxCase.Visible = false;
                    grpBoxQA.Visible = false;

                    btnStartCase.Enabled = true;
                    btnCloseCase.Enabled = false;
                    btnHoldCase.Enabled = false;
                    btnCancelCase.Enabled = false;
                    comboBoxUserSelect.SelectedItem = null;
                }
            }
            catch (Exception E)
            {
                LogException(E);
            }
            finally
            {
                if (CM != null) LogMethodEnd(CM);
                Cursor = Cursors.Default;
            }


        }

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

                if (Program.Collector == null)
                    return;

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

                if (Program.Collector.F4SDAnalyticsValid && SessionId != null)
                {

                    CaseId = Guid.NewGuid();
                    var caseData = new cF4SDCaseParameters();
                    caseData.SessionId = SessionId;
                    caseData.CaseId = CaseId;
                    caseData.UserId = Userid;
                    if (comboBoxUserSelect.SelectedItem != null)
                    {
                        var RetVal = new List<cDataHistoryInfoClassListEntry>();
                        var user = comboBoxUserSelect.SelectedItem;
                        RetVal.Add((cDataHistoryInfoClassListEntry)user);
                        caseData.UserId = RetVal[0].id;
                    }


                    bool IsLoaded = await Program.Collector.CreateCaseAsync(caseData, _requestInfo, 1, CancellationToken.None);
                    btnStartCase.Enabled = false;
                    grpBoxQA.Visible = true;
                    btnCloseCase.Enabled = true;
                    btnCancelCase.Enabled = true;
                    btnHoldCase.Enabled = true;
                }
            }
            catch (Exception E)
            {
                LogException(E);
            }
            finally
            {
                if (CM != null) LogMethodEnd(CM);
                Cursor = Cursors.Default;
            }
        }

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

                //btnInsertSession.Enabled = false;
                if (Program.Collector == null)
                    return;

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

                if (Program.Collector.F4SDAnalyticsValid && SessionId != null && CaseId != null)
                {
                    var caseStatus = new cF4SDCaseTimeParameters();

                    caseStatus.CaseId = CaseId;
                    caseStatus.StatusId = CaseStatus.Canceled;

                    bool IsLoaded = await Program.Collector.UpdateCaseStateAsync(caseStatus, _requestInfo, 1, CancellationToken.None);
                    btnStartCase.Enabled = true;
                    grpBoxQA.Visible = false;
                    btnCloseCase.Enabled = false;
                    btnCancelCase.Enabled = false;
                    btnHoldCase.Enabled = false;
                    comboBoxUserSelect.SelectedItem = null;
                }
            }
            catch (Exception E)
            {
                LogException(E);
            }
            finally
            {
                if (CM != null) LogMethodEnd(CM);
                Cursor = Cursors.Default;
            }
        }

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

                //btnInsertSession.Enabled = false;
                if (Program.Collector == null)
                    return;

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

                if (Program.Collector.F4SDAnalyticsValid && SessionId != null && CaseId != null)
                {
                    var caseStatus = new cF4SDCaseTimeParameters();

                    caseStatus.CaseId = CaseId;
                    caseStatus.StatusId = CaseStatus.InProgress;

                    bool IsLoaded = await Program.Collector.UpdateCaseStateAsync(caseStatus, _requestInfo, 1, CancellationToken.None);
                    btnStartCase.Enabled = true;
                    grpBoxQA.Visible = false;
                    btnCloseCase.Enabled = false;
                    btnCancelCase.Enabled = false;
                    btnHoldCase.Enabled = false;

                    comboBoxUserSelect.SelectedItem = null;

                }
            }
            catch (Exception E)
            {
                LogException(E);
            }
            finally
            {
                if (CM != null) LogMethodEnd(CM);
                Cursor = Cursors.Default;
            }
        }

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

                //btnInsertSession.Enabled = false;
                if (Program.Collector == null)
                    return;

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

                if (Program.Collector.F4SDAnalyticsValid && SessionId != null && CaseId != null)
                {

                    var caseStatus = new cF4SDCaseTimeParameters();
                    caseStatus.CaseId = CaseId;

                    if (btnHoldCase.Text == "Hold")
                    {
                        btnHoldCase.Text = "Continue";
                        caseStatus.StatusId = CaseStatus.Finished;
                        grpBoxQA.Visible = false;
                        btnCancelCase.Enabled = false;
                        btnCloseCase.Enabled = false;
                    }
                    else if (btnHoldCase.Text == "Continue")
                    {
                        btnHoldCase.Text = "Hold";
                        caseStatus.StatusId = CaseStatus.OnHold;
                        grpBoxQA.Visible = true;
                        btnCancelCase.Enabled = true;
                        btnCloseCase.Enabled = true;
                    }


                    bool IsLoaded = await Program.Collector.UpdateCaseStateAsync(caseStatus, _requestInfo, 1, CancellationToken.None);


                }
            }
            catch (Exception E)
            {
                LogException(E);
            }
            finally
            {
                if (CM != null) LogMethodEnd(CM);
                Cursor = Cursors.Default;
            }
        }

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

                //btnInsertSession.Enabled = false;
                if (Program.Collector == null)
                    return;

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

                if (Program.Collector.F4SDAnalyticsValid && SessionId != null && CaseId != null)
                {
                    var caseStatus = new cF4SDCaseTimeParameters();

                    caseStatus.CaseId = CaseId;
                    caseStatus.StatusId = CaseStatus.Canceled;

                    bool IsLoaded = await Program.Collector.UpdateCaseStateAsync(caseStatus, _requestInfo, 1, CancellationToken.None);
                    btnStartCase.Enabled = true;
                    btnCreateSession.Enabled = false;
                }
            }
            catch (Exception E)
            {
                LogException(E);
            }
            finally
            {
                if (CM != null) LogMethodEnd(CM);
                Cursor = Cursors.Default;
            }

        }

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

                //btnInsertSession.Enabled = false;
                if (Program.Collector == null)
                    return;

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

                if (Program.Collector.F4SDAnalyticsValid && SessionId != null && CaseId != null)
                {
                    var quickAction = new cF4SDQuickActionParameters();

                    quickAction.CaseId = CaseId;
                    quickAction.QuickActionId = Guid.NewGuid();
                    quickAction.Paramaters = null;
                    quickAction.Result = null;
                    quickAction.ErrorCode = 0;
                    quickAction.ErrorDescription = null;
                    quickAction.Start = DateTime.Now;
                    quickAction.Finish = DateTime.Now;

                    await Program.Collector.ReportQuickActionExecutionAsync(quickAction, Program.Collector.F4SDAnalyticsDb.Connection, _requestInfo, 1, CancellationToken.None);
                    await Program.Collector.ReportQuickActionExecutionAsync(quickAction, Program.Collector.InfrastructureConfig.HistoryDB.Connection, _requestInfo, 1, CancellationToken.None);

                }
            }
            catch (Exception E)
            {
                LogException(E);
            }
            finally
            {
                if (CM != null) LogMethodEnd(CM);
                Cursor = Cursors.Default;
            }

        }

        private async void ctrlMainFunction_Load(object sender, EventArgs e)
        {
            btnCloseSession.Enabled = false;
            grpBoxCase.Visible = false;
            grpBoxQA.Visible = false;

            if (Program.mainForm == null)
                return;

            var _requestInfo = new cF4sdWebRequestInfo("ctrlMainFunction_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());
            SessionCheck = new System.Timers.Timer(60.0 * 1000 * Program.Collector.InfrastructureConfig.F4SDAnalyticsDB.SessionCheckInterval);
            SessionCheck.Elapsed += Program.Collector.CheckSessionsAsync;
            SessionCheck.Start();

            CaseCheck = new System.Timers.Timer(60.0 * 1000 * Program.Collector.InfrastructureConfig.F4SDAnalyticsDB.CaseCheckInterval);
            CaseCheck.Elapsed += Program.Collector.CheckCasesAsync;
            CaseCheck.Start();
        }

    }
}
