using System;
using System.Collections.Generic;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;

using Newtonsoft.Json;

using C4IT.FASD.Base;
using C4IT.HTTP;
using C4IT.Security;
using FasdCockpitCommunication;
using FasdCockpitBase;

using static C4IT.Logging.cLogManager;

namespace FasdDesktopUi.Basics
{
    public class cExternalToolExecutorEnh : cExternalToolExecutor
    {
        public static async Task<cProcessResult> StartServerActionAsync(cF4sdQuickActionServer ServerAction, cSupportCaseDataProvider dataProvider, string ProgramTitle, Dictionary<cAdjustableParameter, object> ParameterDictionary = null)
        {
            cProcessResult _resultProcess = new cProcessResult(0);
            var CM = MethodBase.GetCurrentMethod();
            LogMethodBegin(CM);

            var apiError = 0;

            try
            {
                var http = GetHttpHelper(false);

                var searchResultInfoClass = cF4sdIdentityEntry.GetFromSearchResult(enumF4sdSearchResultClass.Computer);
                var parameter = new cF4SDServerQuickActionParameters() { Action = ServerAction.Action, Category = ServerAction.Category, ParamaterType = ServerAction.ParameterType, Identities = dataProvider.Identities, AdjustableParameter = ParameterDictionary };
                var payload = JsonConvert.SerializeObject(parameter);

                var result = await http.PostJsonAsync("api/QuickAction/Run", payload, 15000, CancellationToken.None);

                if (!result.IsOk)
                {
                    apiError = (int)result.Status;
                    _resultProcess.ReturnCode = (int)result.Status;

                }
                _resultProcess.StandardOutput = result.Result;
            }
            catch (Exception E)
            {
                apiError = E.HResult;
                LogException(E);
            }
            finally
            {

                LogMethodEnd(CM);
            }


            return _resultProcess;
        }

        public static cHttpHelper GetHttpHelper(bool useToken)
        {
            try
            {


                return new cHttpHelper(cFasdCockpitMachineConfiguration.Instance.ServerUrl, GetOneTimePw().GetCredential(), false);
            }
            catch (Exception E)
            {
                LogException(E);
            }

            return null;
        }

        public static cOneTimePW GetOneTimePw()
        {
            return new cOneTimePW("OneTimePw", cSecurePassword.Instance);
        }
    }
}
