using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using C4IT.F4SD.DisplayFormatting;
using C4IT.F4SD.SupportCaseProtocoll.Models;
using C4IT.FASD.Base;
using C4IT.Logging;
using C4IT.MultiLanguage;

using FasdCockpitBase.Models;

using FasdDesktopUi.Basics.Models;
using FasdDesktopUi.Basics.Services.ProtocollService;
using FasdDesktopUi.Basics.UserControls;

using static FasdDesktopUi.Basics.UserControls.QuickActionStatusMonitor;

namespace FasdDesktopUi.Basics.UiActions
{
    public class cUiDemoQuickAction : cUiQuickAction
    {
        public cF4sdQuickActionDemo quickActionDemo { get; private set; }

        public cUiDemoQuickAction(cF4sdQuickActionDemo QuickActionConfig) : base(QuickActionConfig)
        {
            quickActionDemo = QuickActionConfig;
            Name = QuickActionConfig.Name;
        }

        public override async Task<cDataCanvasDataModel> GetQuickActionDataAsync(cSupportCaseDataProvider dataProvider, bool isDetailedLayout)
        {
            await Task.CompletedTask;

            DataProvider = dataProvider;

            var detailedData = new cDetailedDataModel() { Heading = "Demo QuickAction" };

            //Get QuickAciton Data
            detailedData.FullDetailedData = new List<object>()
            {
                new List<object>() { "Status", cMultiLanguageSupport.GetItem("QuickAction.Revision.ExecutionTime")},
                new List<object>() { cMultiLanguageSupport.GetItem("QuickAction.Revision.Status.FinishedSuccessfull"), cUtility.RawValueFormatter.GetDisplayValue(DateTime.UtcNow.AddMinutes(-5), RawValueType.DATETIME)},
                new List<object>() { cMultiLanguageSupport.GetItem("QuickAction.Revision.Status.FinishedSuccessfull"), cUtility.RawValueFormatter.GetDisplayValue(DateTime.UtcNow.AddMinutes(-38), RawValueType.DATETIME) },
                new List<object>() { cMultiLanguageSupport.GetItem("QuickAction.Revision.Status.FinishedWithError"), cUtility.RawValueFormatter.GetDisplayValue(DateTime.UtcNow.AddHours(-2).AddMinutes(12), RawValueType.DATETIME) },
                new List<object>() { cMultiLanguageSupport.GetItem("QuickAction.Revision.Status.FinishedSuccessfull"), cUtility.RawValueFormatter.GetDisplayValue(DateTime.UtcNow.AddDays(-1).AddHours(4).AddMinutes(-32), RawValueType.DATETIME) },
                new List<object>() { cMultiLanguageSupport.GetItem("QuickAction.Revision.Status.FinishedWithError"), cUtility.RawValueFormatter.GetDisplayValue(DateTime.UtcNow.AddDays(-1).AddHours(4).AddMinutes(-34), RawValueType.DATETIME) }
            };

            //Get Process Steps of Action
            var quickActionData = new cQuickActionStatusMonitorModel()
            {
                ActionName = Name,
                QuickActionDefinition = quickActionDemo,
                ActionSteps = new List<cQuickActionStatusMonitorModel.cQuickActionStep>(),
                QuickActionParameters = quickActionDemo.AdjustableParameters,
                RunQuickAction = ProcessActionAsync
            };

            if (quickActionDemo.QuickActionType == enumQuickActionExecutionType.LocalScript)
            {
                quickActionData.ActionSteps.Add(new cQuickActionStatusMonitorModel.cQuickActionStep(cMultiLanguageSupport.GetItem("QuickAction.Local.Load"), quickActionDemo.Name, cQuickActionStatusMonitorModel.cQuickActionStep.enumActionStepType.running));
            }
            else
            {
                if (quickActionDemo.SimulatedClientConnect > 0)
                    quickActionData.ActionSteps.Add(new cQuickActionStatusMonitorModel.cQuickActionStep(cMultiLanguageSupport.GetItem("QuickAction.Remote.Connect"), quickActionDemo.Name, cQuickActionStatusMonitorModel.cQuickActionStep.enumActionStepType.connectingToClient));
                if (quickActionDemo.SimulatedRuntime > 0)
                    quickActionData.ActionSteps.Add(new cQuickActionStatusMonitorModel.cQuickActionStep(cMultiLanguageSupport.GetItem("QuickAction.Remote.Running"), quickActionDemo.Name, cQuickActionStatusMonitorModel.cQuickActionStep.enumActionStepType.running));
            }

            cRecommendationDataModel recommendationData = QuickActionRecommendation?.Recommendation != null ? QuickActionRecommendation : null;

            return new cDataCanvasDataModel() { DetailedData = detailedData, QuickActionStatusMonitorData = quickActionData, RecommendationData = recommendationData };
        }

        public override async Task<List<object>> ProcessActionAsync(CancellationToken token, Dictionary<cAdjustableParameter, object> ParameterDictionary = null)
        {
            var _finshedStatus = enumQuickActionRevisionStatus.finishedSuccessfull;
            if (quickActionDemo.SimulatedClientConnect > 0)
            {
                try { await Task.Delay(quickActionDemo.SimulatedClientConnect * 1000, token); }
                catch (TaskCanceledException) { }

                if (token.IsCancellationRequested)
                    _finshedStatus = enumQuickActionRevisionStatus.canceled;
                cQuickActionStatusMonitorModel.cQuickActionStep.SetQuickActionStepStatuses(StatusMonitor.QuickActionData.ActionSteps, quickActionDemo.Name, cQuickActionStatusMonitorModel.cQuickActionStep.enumActionStepType.connectingToClient, _finshedStatus);
            }

            if (quickActionDemo.SimulatedRuntime > 0)
            {
                if (!token.IsCancellationRequested)
                    try { await Task.Delay(quickActionDemo.SimulatedRuntime * 1000, token); }
                    catch (TaskCanceledException) { }

                if (token.IsCancellationRequested)
                    _finshedStatus = enumQuickActionRevisionStatus.canceled;

                cQuickActionStatusMonitorModel.cQuickActionStep.SetQuickActionStepStatuses(StatusMonitor.QuickActionData.ActionSteps, quickActionDemo.Name, cQuickActionStatusMonitorModel.cQuickActionStep.enumActionStepType.running, _finshedStatus);
            }

            string _msg;
            if (_finshedStatus == enumQuickActionRevisionStatus.canceled)
            {
                _msg = cMultiLanguageSupport.GetItem("QuickAction.Revision.Status.Canceled");
                cQuickActionStatusMonitorModel.cQuickActionStep.CancelRemainingQuickActionSteps(StatusMonitor.QuickActionData.ActionSteps);
            }
            else
            {
                if (quickActionDemo?.QuickActionMeasureResults?.Count > 0 && quickActionDemo.QuickActionMeasures?.Count > 0)
                {
                    var measureValues = cUiRemoteQuickAction.GetStatusMonitorMeasureValues(quickActionDemo.QuickActionMeasureResults.Values.ToList(), quickActionDemo.QuickActionMeasures);
                    if (measureValues?.Count > 0)
                        StatusMonitor.MeasureValues = measureValues;
                }

                cQuickActionOutput quickActionOutput = null;
                var _ref = new cF4sdQuickActionRevision();

                if (!string.IsNullOrEmpty(quickActionDemo?.DemoResult))
                    try
                    {
                        dynamic retValue = Newtonsoft.Json.JsonConvert.DeserializeObject(quickActionDemo?.DemoResult);
                        var _output = new cF4sdQuickActionRevision.cOutput()
                        {
                            ResultCode = quickActionDemo.QuickActionSuccess,
                            Values = retValue
                        };

                        _ref.OutputText = Newtonsoft.Json.JsonConvert.SerializeObject(_output);
                    }
                    catch { }

                StatusMonitor.QuickActionOutputs.Add(_ref.Output);
                quickActionOutput = QuickActionStatusMonitor.cQuickActionOutput.GetQuickActionOutput(_ref.Output, DataProvider);

                cQuickActionCopyData copyData = QuickActionProtocollEntryOutput.GetCopyData(quickActionDemo, DataProvider, true, quickActionOutput, StatusMonitor.MeasureValues);
                QuickActionProtocollEntry protocollEntry = QuickActionProtocollEntryOutput.GetQuickActionProtocollEntry(quickActionDemo, copyData);

                F4SDProtocoll.Instance.Add(protocollEntry);

                _msg = cMultiLanguageSupport.GetItem("QuickAction.Revision.Status.FinishedSuccessfull");
            }

            return new List<object>() { _msg, cUtility.RawValueFormatter.GetDisplayValue(DateTime.UtcNow, RawValueType.DATETIME) };
        }
    }
}
