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

namespace MainShell.Process
{
    public class DiePositionActivity : ActivityAbstractBase
    {
        private readonly DiePositionService _diePositionService;

        public DiePositionActivity(string name, DiePositionService diePositionService)
            : base(name)
        {
            _diePositionService = diePositionService ?? throw new ArgumentNullException(nameof(diePositionService));
        }

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

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

                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(string.Format("晶圆定位活动执行失败：{0}", errorMessage));
                return Fail(context, failureMessageKey, failureMessageArguments);
            }

            return ActivityResult.Success;
        }

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