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

namespace MainShell.Process
{
    public class ChipUnloadRequestActivity : ActivityAbstractBase
    {
        public ChipUnloadRequestActivity(string name, TimeSpan? timeout = null) : base(name)
        {
        }

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

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

            ChipPreparationRequest request = new ChipPreparationRequest
            {
                RecipeName = ResolveRecipeName(context),
                Action = ChipPreparationAction.Unload,
                SourceStepId = ResolveSourceStepId(context)
            };

            string rejectReason;
            if (preparationAreaService.TryRequestPrepare(request, out rejectReason))
            {
                context.SetData(WorkflowContextKeys.PreparationAreaStatus, preparationAreaService.CurrentStatus);
                return Task.FromResult(ActivityResult.Success);
            }

            return Task.FromResult(Fail(
                context,
                MessageKey.ProcessStepFailedWithReason,
                new object[]
                {
                    Name,
                    string.IsNullOrWhiteSpace(rejectReason) ? "芯片后台下料请求被拒绝。" : rejectReason
                }));
        }

        private static string ResolveRecipeName(WorkflowContext context)
        {
            if (context.TryGetData<RecipeManager>(WorkflowContextKeys.RecipeManager, out var recipeManager) &&
                recipeManager != null &&
                recipeManager.CurrentWaferRecipe != null)
            {
                return recipeManager.CurrentWaferRecipe.RecipeName;
            }

            return string.Empty;
        }

        private static string ResolveSourceStepId(WorkflowContext context)
        {
            if (context.TryGetData<string>(WorkflowContextKeys.CurrentStepId, out var stepId))
            {
                return stepId;
            }

            return string.Empty;
        }
    }
}
