using Hcs.WebApp.Data.Hcs;
using Hcs.WebApp.Services;
using Microsoft.EntityFrameworkCore;

namespace Hcs.WebApp.BackgroundServices.CampaignManagers
{
    public class ExportCommonRegistryElementsManager_15_7_0_1(
        IServiceScopeFactory scopeFactory,
        OperationExecutionState operationExecutionState,
        ResultWaitState resultWaitState,
        Campaign campaign) : ManagerBase(scopeFactory, operationExecutionState, resultWaitState, campaign)
    {
        private enum Step
        {
            Start = 0,
            ExecutionWait = 1,
            ResultWait = 2,
            End = 3
        }

        private RegistryService? registryService;

        protected RegistryService RegistryService => registryService ??= scope.ServiceProvider.GetRequiredService<RegistryService>();

        public override async Task ProcessAsync()
        {
            switch ((Step)campaign.Step)
            {
                case Step.Start:
                    await DoStartStepAsync();
                    break;

                case Step.ExecutionWait:
                    await DoExecutionWaitStepAsync();
                    break;

                case Step.ResultWait:
                    await DoResultWaitStepAsync();
                    break;
            }
        }

        private async Task DoStartStepAsync()
        {
            IEnumerable<Operation>? operations = null;

            using var context = HeadquartersService.GetNewContext();
            var executionStrategy = context.Database.CreateExecutionStrategy();
            await executionStrategy.ExecuteAsync(async () =>
            {
                using var transaction = await context.Database.BeginTransactionAsync();
                try
                {
                    await HeadquartersService.SetCampaignStartedAsync(context, campaign.Id);

                    campaign.Step = (int)Step.ExecutionWait;
                    await HeadquartersService.UpdateCampaignStepAsync(context, campaign);

                    var registryCount = await RegistryService.GetRegistryCountAsync(context, true);
                    operations = await HeadquartersService.InitiateOperationsAsync(context, registryCount, campaign.Id, Operation.OperationType.NsiCommon_ExportNsiItem_15_7_0_1);
                    await RegistryService.SetOperationsToRegistriesAsync(context, true, operations);

                    await transaction.CommitAsync();
                }
                catch
                {
                    transaction?.Rollback();

                    throw;
                }
            });

            if (operations != null)
            {
                foreach (var operation in operations)
                {
                    operationExecutionState.EnqueueOperation(operation);
                }
            }

            State = IManager.ManagerState.Started;
        }

        private async Task DoExecutionWaitStepAsync()
        {
            if (operationExecutionState.HasCampaignOperation(campaign.Id)) return;

            campaign.Step = (int)Step.ResultWait;
            await HeadquartersService.UpdateCampaignStepAsync(campaign);

            var operations = await HeadquartersService.GetOperationsAsync(campaign.Id);
            foreach (var operation in operations)
            {
                if (!string.IsNullOrEmpty(operation.MessageGuid))
                {
                    resultWaitState.EnqueueOperation(operation);
                }
            }
        }

        private async Task DoResultWaitStepAsync()
        {
            if (resultWaitState.HasCampaignOperation(campaign.Id)) return;

            using var context = HeadquartersService.GetNewContext();
            var executionStrategy = context.Database.CreateExecutionStrategy();
            await executionStrategy.ExecuteAsync(async () =>
            {
                using var transaction = await context.Database.BeginTransactionAsync();
                try
                {
                    campaign.Step = (int)Step.End;
                    await HeadquartersService.UpdateCampaignStepAsync(context, campaign);

                    await HeadquartersService.SetCampaignEndedAsync(context, campaign.Id);

                    await transaction.CommitAsync();
                }
                catch
                {
                    transaction?.Rollback();

                    throw;
                }
            });

            State = IManager.ManagerState.Ended;
        }
    }
}
