using Valg.EVA.Skanning.Contracts;
using Valg.EVA.Skanning.Diagnostics;
using Valg.EVA.Skanning.Identity;
using Valg.EVA.Skanning.Services;
using Valg.EVA.Skanning.Services.Verification;
using Valg.EVA.Skanning.ServicesModel.ServiceContracts.Verification.Read;

namespace Valg.EVA.Skanning.Verify.Startup.VerifyBallotPaper.ReadModel
{
    public class ReadModelHub : IReadModelHub
    {
        private readonly IIdentityProvider identityProvider;
        private readonly ITimingProbe timingProbe;
        private readonly IVerificationService verificationService;
        private readonly IDatabaseConfiguration databaseConfiguration;

        public ReadModelHub(IIdentityProvider identityProvider, 
            ITimingProbe timingProbe, 
            IVerificationService verificationService,
            IDatabaseConfiguration databaseConfiguration)
        {
            this.identityProvider = identityProvider;
            this.timingProbe = timingProbe;
            this.verificationService = verificationService;
            this.databaseConfiguration = databaseConfiguration;
        }

        public GetNextBallotPaperToVerifyResult GetNextBallotPaper(int currentBoxCountingId)
        {
            GetNextBallotPaperToVerifyResult getNextResult = null;
            timingProbe.Measure(() =>
            {
                getNextResult = verificationService.GetNextBallotPaperToVerify(new GetNextBallotPaperToVerifyParameters
                {
                    BoxCountingId = currentBoxCountingId,
                    UserRequestingTheBallotPaper = identityProvider.GetCurrentUserName()
                });
            },
                () => new DefaultMeasurementEventData(identityProvider.CurrentSelectedRole.CountingEmlAreaContextId,
                        (int)ServicesInstrumentedEvents.GetBallotPaper, ServicesInstrumentedEvents.GetBallotPaper.ToString(), 
                        databaseConfiguration.DatabaseServerName));

            return getNextResult;
        }

        public GetBallotPaperResult GetBallotPaper(int ballotPaperId)
        {
            return verificationService.GetBallotPaper(new GetBallotPaperParameters
            {
                BallotPaperId = ballotPaperId,
                CountingEmlAreaContextId = identityProvider.CurrentSelectedRole.CountingEmlAreaContextId
            });
        }

        public bool IsBoxStillOpenForVerification(int boxCountingId)
        {
            return verificationService.IsBoxStillOpenForVerification(boxCountingId);
        }

        public int[] GetBallotIdsVerified(int boxCountingId)
        {
            return verificationService.GetBallotPaperIdsVerified(
                    new GetBallotPaperIdsVerifiedParameters
                    {
                        BoxCountingId = boxCountingId, FilterByUser = identityProvider.GetCurrentUserName()
                    }).BallotPaperIds;
        }
    }
}
