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 System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using static C4IT.Logging.cLogManager;
using static FasdDesktopUi.Basics.UserControls.QuickActionStatusMonitor;

namespace FasdDesktopUi.Basics.UiActions
{
    public class cUiLocalWebRequestQuickAction : cUiLocalQuickAction
    {
        public cF4sdQuickActionLocalWebRequest WebRequestQuickAction { get; set; }

        public cUiLocalWebRequestQuickAction(cF4sdQuickActionLocalWebRequest webRequestQuickAction) : base(webRequestQuickAction)
        {
            WebRequestQuickAction = webRequestQuickAction;
        }


        private string GetUrl()
        {
            string output = string.Empty;
            try
            {
                if (WebRequestQuickAction?.QueryString is null)
                    return output;

                if (!string.IsNullOrEmpty(WebRequestQuickAction.QueryString.ConstValue))
                {
                    output = WebRequestQuickAction.QueryString.ConstValue;
                }
                else
                {
                    var queryStringParameterName = WebRequestQuickAction.QueryString.ParameterName;
                    if (!string.IsNullOrEmpty(queryStringParameterName))
                        if (DataProvider.NamedParameterEntries.TryGetValue(queryStringParameterName, out var namedParameterEntry))
                            output = namedParameterEntry.GetValue();
                }

                if (string.IsNullOrEmpty(output))
                    return output;

                if (WebRequestQuickAction.QueryParameters?.Count <= 0)
                    return output;

                foreach (var queryParameter in WebRequestQuickAction.QueryParameters)
                {
                    if (string.IsNullOrEmpty(queryParameter.QueryParameterName))
                        continue;

                    var replacementString = string.Empty;

                    if (!string.IsNullOrEmpty(queryParameter.ConstValue))
                    {
                        replacementString = queryParameter.ConstValue;
                    }
                    else
                    {
                        var queryStringParameterName = queryParameter.ParameterName;
                        if (!string.IsNullOrEmpty(queryStringParameterName))
                            if (DataProvider.NamedParameterEntries.TryGetValue(queryStringParameterName, out var namedParameterEntry))
                                replacementString = queryParameter.UseHtmlValue ? namedParameterEntry.GetHtmlValue() : namedParameterEntry.GetHtmlValue();
                    }

                    output = output.Replace(queryParameter.QueryParameterName, replacementString);
                }
            }
            catch (Exception E)
            {
                LogException(E);
            }

            return output;
        }

        public override async Task<List<object>> ProcessActionAsync(CancellationToken token, Dictionary<cAdjustableParameter, object> ParameterDictionary = null)
        {
            try
            {
                //todo: use ParameterDictionary if request has Parameters                

                await Task.CompletedTask;

                cBrowsers browsers = new cBrowsers();
                string webRequestUrl = GetUrl();

                browsers.Start(WebRequestQuickAction.BrowserName, webRequestUrl);

                if (string.IsNullOrEmpty(webRequestUrl))
                {
                    cQuickActionStatusMonitorModel.cQuickActionStep.SetQuickActionStepStatuses(StatusMonitor.QuickActionData.ActionSteps, LocalQuickAction.Name, cQuickActionStatusMonitorModel.cQuickActionStep.enumActionStepType.main, enumQuickActionRevisionStatus.canceled);
                    cQuickActionStatusMonitorModel.cQuickActionStep.SetQuickActionStepStatuses(StatusMonitor.QuickActionData.ActionSteps, LocalQuickAction.Name, cQuickActionStatusMonitorModel.cQuickActionStep.enumActionStepType.running, enumQuickActionRevisionStatus.canceled);

                    return new List<object>() { cMultiLanguageSupport.GetItem("QuickAction.Revision.Status.FinishedWithError"), cUtility.RawValueFormatter.GetDisplayValue(DateTime.UtcNow, RawValueType.DATETIME) };
                }

                cQuickActionOutput quickActionOutput = new cQuickActionOutputSingle(new cF4sdQuickActionRevision.cOutput() { ResultCode = enumQuickActionSuccess.unknown }); ;
                cQuickActionOutput protocollOutput = new cQuickActionOutputSingle(new cF4sdQuickActionRevision.cOutput() { ResultCode = enumQuickActionSuccess.unknown }); ;


                if (!token.IsCancellationRequested)
                {
                    cQuickActionStatusMonitorModel.cQuickActionStep.SetQuickActionStepStatuses(StatusMonitor.QuickActionData.ActionSteps, LocalQuickAction.Name, cQuickActionStatusMonitorModel.cQuickActionStep.enumActionStepType.main, enumQuickActionRevisionStatus.finishedSuccessfull);
                    cQuickActionStatusMonitorModel.cQuickActionStep.SetQuickActionStepStatuses(StatusMonitor.QuickActionData.ActionSteps, LocalQuickAction.Name, cQuickActionStatusMonitorModel.cQuickActionStep.enumActionStepType.running, enumQuickActionRevisionStatus.finishedSuccessfull);

                    quickActionOutput = new cQuickActionOutputSingle(new cF4sdQuickActionRevision.cOutput() { ResultCode = enumQuickActionSuccess.finished });

                    if (cF4SDCockpitXmlConfig.Instance.HealthCardConfig.ProtocollLanguage != null)
                    {
                        string tempLang = cMultiLanguageSupport.CurrentLanguage;
                        cMultiLanguageSupport.CurrentLanguage = cF4SDCockpitXmlConfig.Instance.HealthCardConfig.ProtocollLanguage;
                        protocollOutput = new cQuickActionOutputSingle(new cF4sdQuickActionRevision.cOutput() { ResultCode = enumQuickActionSuccess.finished });
                        cMultiLanguageSupport.CurrentLanguage = tempLang;
                    }

                    cQuickActionCopyData copyData = QuickActionProtocollEntryOutput.GetCopyData(LocalQuickAction, DataProvider, false, protocollOutput, StatusMonitor.MeasureValues);
                    QuickActionProtocollEntry protocollEntry = QuickActionProtocollEntryOutput.GetQuickActionProtocollEntry(LocalQuickAction, copyData);

                    F4SDProtocoll.Instance.Add(protocollEntry);

                    return new List<object>() { cMultiLanguageSupport.GetItem("QuickAction.Revision.Status.FinishedSuccessfull"), cUtility.RawValueFormatter.GetDisplayValue(DateTime.UtcNow, RawValueType.DATETIME) };
                }
                else
                {
                    cQuickActionStatusMonitorModel.cQuickActionStep.SetQuickActionStepStatuses(StatusMonitor.QuickActionData.ActionSteps, LocalQuickAction.Name, cQuickActionStatusMonitorModel.cQuickActionStep.enumActionStepType.main, enumQuickActionRevisionStatus.canceled);
                    cQuickActionStatusMonitorModel.cQuickActionStep.SetQuickActionStepStatuses(StatusMonitor.QuickActionData.ActionSteps, LocalQuickAction.Name, cQuickActionStatusMonitorModel.cQuickActionStep.enumActionStepType.running, enumQuickActionRevisionStatus.canceled);

                    quickActionOutput = new cQuickActionOutputSingle(new cF4sdQuickActionRevision.cOutput() { ResultCode = enumQuickActionSuccess.error, ErrorDescription = cMultiLanguageSupport.GetItem("QuickAction.Copy.Output.Cancel") });

                    string tempLang = cMultiLanguageSupport.CurrentLanguage;
                    if (cF4SDCockpitXmlConfig.Instance.HealthCardConfig.ProtocollLanguage != null)
                        cMultiLanguageSupport.CurrentLanguage = cF4SDCockpitXmlConfig.Instance.HealthCardConfig.ProtocollLanguage;

                    protocollOutput = new cQuickActionOutputSingle(new cF4sdQuickActionRevision.cOutput() { ResultCode = enumQuickActionSuccess.error, ErrorDescription = cMultiLanguageSupport.GetItem("QuickAction.Copy.Output.Cancel") });
                    cQuickActionCopyData copyData = QuickActionProtocollEntryOutput.GetCopyData(LocalQuickAction, DataProvider, false, protocollOutput, StatusMonitor.MeasureValues);
                    QuickActionProtocollEntry protocollEntry = QuickActionProtocollEntryOutput.GetQuickActionProtocollEntry(LocalQuickAction, copyData);

                    F4SDProtocoll.Instance.Add(protocollEntry);
                    cMultiLanguageSupport.CurrentLanguage = tempLang;

                    return new List<object>() { cMultiLanguageSupport.GetItem("QuickAction.Revision.Status.Canceled"), cUtility.RawValueFormatter.GetDisplayValue(DateTime.UtcNow, RawValueType.DATETIME) };
                }
            }
            catch (Exception E)
            {
                LogException(E);
                return new List<object>() { cMultiLanguageSupport.GetItem("QuickAction.Revision.Status.FinishedWithError"), cUtility.RawValueFormatter.GetDisplayValue(DateTime.UtcNow, RawValueType.DATETIME) };
            }
            finally
            {
            }
        }
    }
}
