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

namespace MainShell.Process
{
    public class ChipPreparationSyncActivity : ActivityAbstractBase
    {
        private readonly TimeSpan _timeout;

        public ChipPreparationSyncActivity(string name, TimeSpan? timeout = null)
            : base(name)
        {
            _timeout = timeout ?? TimeSpan.FromSeconds(30);
        }

        protected override async Task<ActivityResult> OnExecuteAsync(WorkflowContext context, ActivityControl activityControl)
        {
            SubstrateLifecycleState substrateState;
            if (!context.TryGetData<SubstrateLifecycleState>(WorkflowContextKeys.SubstrateProcessState, out substrateState) ||
                substrateState != SubstrateLifecycleState.HeightMeasured)
            {
                return Fail(
                    context,
                    MessageKey.ProcessStepFailedWithReason,
                    new object[]
                    {
                        Name,
                        "基板尚未完成测高，不能进入芯片同步点。"
                    });
            }

            bool pendingChipLoad;
            if (context.TryGetData<bool>(WorkflowContextKeys.PendingChipLoad, out pendingChipLoad) && !pendingChipLoad)
            {
                return ActivityResult.Success;
            }

            PreparationAreaService preparationAreaService;
            if (!context.TryGetData<PreparationAreaService>(WorkflowContextKeys.PreparationAreaService, out preparationAreaService) || preparationAreaService == null)
            {
                throw new InvalidOperationException("未在工作流上下文中找到准备区服务。");
            }

            ChipPreparationWaitResult waitResult = await preparationAreaService.WaitUntilLoadedAsync(_timeout, activityControl.CancellationToken).ConfigureAwait(false);
            if (!waitResult.Success)
            {
                if (waitResult.IsCanceled)
                {
                    SetWorkflowFailure(context, string.IsNullOrWhiteSpace(waitResult.ErrorMessage) ? "芯片同步等待已取消。" : waitResult.ErrorMessage);
                    return ActivityResult.Canceled;
                }

                return Fail(
                    context,
                    MessageKey.ProcessStepFailedWithReason,
                    new object[]
                    {
                        Name,
                        string.IsNullOrWhiteSpace(waitResult.ErrorMessage) ? "芯片同步等待失败。" : waitResult.ErrorMessage
                    });
            }

            CurrentChipStateService currentChipStateService;
            if (!context.TryGetData<CurrentChipStateService>(WorkflowContextKeys.CurrentChipStateService, out currentChipStateService) || currentChipStateService == null)
            {
                throw new InvalidOperationException("未在工作流上下文中找到当前芯片状态服务。");
            }

            currentChipStateService.SetState(CurrentChipLifecycleState.LoadedPendingTransfer);
            context.SetData(WorkflowContextKeys.CurrentChipState, CurrentChipLifecycleState.LoadedPendingTransfer);
            context.SetData(WorkflowContextKeys.PendingChipLoad, false);
            context.SetData(WorkflowContextKeys.PreparationAreaStatus, preparationAreaService.CurrentStatus);
            return ActivityResult.Success;
        }
    }
}