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

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

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

            CurrentChipLifecycleState currentChipState;
            if (!context.TryGetData<CurrentChipLifecycleState>(WorkflowContextKeys.CurrentChipState, out currentChipState) ||
                currentChipState != CurrentChipLifecycleState.LoadedPendingTransfer)
            {
                return Task.FromResult(ActivityResult.Success);
            }

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

            AutoProductionRuntimeStateService autoProductionRuntimeStateService;
            if (!context.TryGetData<AutoProductionRuntimeStateService>(WorkflowContextKeys.AutoProductionRuntimeStateService, out autoProductionRuntimeStateService) || autoProductionRuntimeStateService == null)
            {
                throw new InvalidOperationException("未在工作流上下文中找到自动流程运行态服务。");
            }

            string rejectReason;
            if (preparationAreaService.TryConsumeReady(out rejectReason))
            {
                CurrentChipStateService currentChipStateService;
                if (context.TryGetData<CurrentChipStateService>(WorkflowContextKeys.CurrentChipStateService, out currentChipStateService) && currentChipStateService != null)
                {
                    currentChipStateService.SetState(CurrentChipLifecycleState.InUse);
                }

                autoProductionRuntimeStateService.SetCurrentChipRemainingCount(1);

                context.SetData(WorkflowContextKeys.PendingChipLoad, false);
                context.SetData(WorkflowContextKeys.CurrentChipState, CurrentChipLifecycleState.InUse);
                context.SetData(WorkflowContextKeys.PreparationAreaStatus, preparationAreaService.CurrentStatus);
                context.SetData(WorkflowContextKeys.CurrentChipRemainingCount, autoProductionRuntimeStateService.CurrentChipRemainingCount);
                return Task.FromResult(ActivityResult.Success);
            }

            return Task.FromResult(Fail(
                context,
                MessageKey.ProcessStepFailedWithReason,
                new object[]
                {
                    Name,
                    string.IsNullOrWhiteSpace(rejectReason) ? "芯片后台准备结果消费失败。" : rejectReason
                }));
        }
    }
}
