using MainShell.Common;
using MainShell.Log;
using MainShell.ProcessResult;
using MW.WorkFlow;
using System;
using System.Linq;
using System.Threading.Tasks;

namespace MainShell.Process
{
    public class SubstrateHeightMeasureActivity : ActivityAbstractBase
    {
        private readonly SubstrateHeightMeasureService _substrateHeightMeasureService;

        public SubstrateHeightMeasureActivity(string name, SubstrateHeightMeasureService substrateHeightMeasureService)
            : base(name)
        {
            _substrateHeightMeasureService = substrateHeightMeasureService ?? throw new ArgumentNullException(nameof(substrateHeightMeasureService));
        }

        protected override async Task<ActivityResult> OnExecuteAsync(WorkflowContext context, ActivityControl activityControl)
        {
            await _substrateHeightMeasureService.ExecuteAsync(context, activityControl).ConfigureAwait(false);

            SubstrateHeightMeasureProcessResult result = context.GetData<SubstrateHeightMeasureProcessResult>(WorkflowContextKeys.SubstrateHeightMeasureResult);
            if (result == null || !result.IsSuccess)
            {
                MessageKey failureMessageKey = result != null && result.ErrorMessageKey != MessageKey.None
                    ? result.ErrorMessageKey
                    : MessageKey.ProcessSubstrateHeightMeasureFailedWithReason;

                object[] failureMessageArguments = result != null
                    ? ConvertToObjectArray(result.ErrorMessageArguments)
                    : new object[] { LanguageResourceHelper.GetString(MessageKey.CommonUnknownError) };

                string errorMessage = result != null && !string.IsNullOrWhiteSpace(result.ErrorMessage)
                    ? result.ErrorMessage
                    : LanguageResourceHelper.Format(failureMessageKey, failureMessageArguments);

                LogManager.LogProcessError($"SubstrateHeightMeasure activity failed: {errorMessage}");
                return Fail(context, failureMessageKey, failureMessageArguments);
            }

            context.SetData(WorkflowContextKeys.SubstrateProcessState, SubstrateLifecycleState.HeightMeasured);
            return ActivityResult.Success;
        }

        private static object[] ConvertToObjectArray(string[] arguments)
        {
            return arguments == null ? Array.Empty<object>() : arguments.Cast<object>().ToArray();
        }
    }
}