using MainShell.Common;
using MW.WorkFlow;
using System.Threading.Tasks;

namespace MainShell.Process
{
    public class PreTransferValidationActivity : ActivityAbstractBase
    {
        public PreTransferValidationActivity(string name)
            : base(name)
        {
        }

        protected override Task<ActivityResult> OnExecuteAsync(WorkflowContext context, ActivityControl activityControl)
        {
            activityControl.ThrowIfCancellationRequested();

            SubstrateLifecycleState substrateState;
            if (!context.TryGetData<SubstrateLifecycleState>(WorkflowContextKeys.SubstrateProcessState, out substrateState) ||
                substrateState != SubstrateLifecycleState.HeightMeasured)
            {
                return Task.FromResult(Fail(
                    context,
                    MessageKey.ProcessStepFailedWithReason,
                    new object[]
                    {
                        Name,
                        "基板状态未完成测高校验。"
                    }));
            }

            bool pendingChipLoad;
            if (!context.TryGetData<bool>(WorkflowContextKeys.PendingChipLoad, out pendingChipLoad))
            {
                pendingChipLoad = false;
            }

            if (pendingChipLoad)
            {
                return Task.FromResult(Fail(
                    context,
                    MessageKey.ProcessStepFailedWithReason,
                    new object[]
                    {
                        Name,
                        "芯片尚未完成上料同步。"
                    }));
            }

            CurrentChipLifecycleState chipState;
            if (!context.TryGetData<CurrentChipLifecycleState>(WorkflowContextKeys.CurrentChipState, out chipState))
            {
                return Task.FromResult(Fail(
                    context,
                    MessageKey.ProcessStepFailedWithReason,
                    new object[]
                    {
                        Name,
                        "当前芯片状态缺失。"
                    }));
            }

            if (chipState != CurrentChipLifecycleState.LoadedPendingTransfer &&
                chipState != CurrentChipLifecycleState.InUse)
            {
                return Task.FromResult(Fail(
                    context,
                    MessageKey.ProcessStepFailedWithReason,
                    new object[]
                    {
                        Name,
                        "芯片状态未达到贴装前要求。"
                    }));
            }

            return Task.FromResult(ActivityResult.Success);
        }
    }
}