using System;
using Valg.EVA.Skanning.Contracts.CommonEnums;
using Valg.EVA.Skanning.Entity.SqlConnection;
using Valg.EVA.Skanning.Entity.WriteModel;
using Valg.EVA.Skanning.Repositories.Counting;

namespace Valg.EVA.Skanning.Commands.StartCounting
{
    public class StartCountingCommandHandler : IHandleCommandsWithReturnValue<StartCountingCommand, int>
    {
        private readonly ICountingWriteableRepository countingWriteable;
        private readonly ICountingRepository countingRepository;
        private readonly TransactionScopeFactory transactionScopeFactory;

        public StartCountingCommandHandler(ICountingWriteableRepository countingWriteable, ICountingRepository countingRepository, TransactionScopeFactory transactionScopeFactory)
        {
            this.countingWriteable = countingWriteable;
            this.countingRepository = countingRepository;
            this.transactionScopeFactory = transactionScopeFactory;
        }

        public void HandleCommand(StartCountingCommand command)
        {
            using (var scope = transactionScopeFactory.GetTransactionScope())
            {
                var potentialActiveCounting = countingRepository.GetActiveCounting(
                    command.UniqueId,
                    command.CountingEmlAreaContextId,
                    null);
                if (potentialActiveCounting != null)
                {
                    throw new InvalidOperationException("Cannot insert two active countings");
                }
                else
                {
                    var countingId = countingWriteable.InsertCounting(new CountingInsert
                    {
                        CountingType = command.CountingType,
                        UniqueId = command.UniqueId,
                        CountingState = CountingState.Active,
                        ElectionEventId = command.ElectionEventId,
                        ContestId = command.ContestId,
                        EmlAreaContextId = command.EmlAreaContextId,
                        CountingEmlAreaContextId = command.CountingEmlAreaContextId,
                        VotingCategory = command.VotingCategory,
                        ElectionIdentifier = command.ElectionIdentifier,
                        ElectionGroup = command.ElectionGroup,
                        CreatedBy = command.CreatedBy,
                        IsProcessedInEmergencyMode= command.IsInEmergencyMode
                    });

                    CommandResult = countingId;
                    scope.Complete();    
                }
            }
        }

        public int CommandResult { get; private set; }
    }
}

