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 SubstratePositionActivity : ActivityAbstractBase
    {
        private readonly SubstratePositionMotionService _motionService;

        public SubstratePositionActivity(string name, SubstratePositionMotionService motionService)
            : base(name)
        {
            _motionService = motionService ?? throw new ArgumentNullException(nameof(motionService));
        }

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

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

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

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

                LogManager.LogSysError($"SubstratePosition activity failed: {errorMsg}");
                return Fail(context, failureMessageKey, failureMessageArguments);
            }

            context.SetData(WorkflowContextKeys.SubstrateProcessState, SubstrateLifecycleState.Positioned);

            return ActivityResult.Success;
        }

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

        protected override void PrepareExecute(WorkflowContext context, ActivityControl activityControl)
        {
        }

        protected override void AfterExecute(WorkflowContext context, ActivityControl activityControl)
        {
        }
    }
}