using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;
using Valg.EVA.Skanning.Contracts.CommonEnums;
using Valg.EVA.Skanning.Entity.ReadModel;
using Valg.EVA.Skanning.Entity.SqlConnection;

namespace Valg.EVA.Skanning.Repositories.Transfers
{
    public class TransferRepository : ITransferRepository
    {
        private readonly ISqlConnectionFactory connectionFactory;

        public TransferRepository(ISqlConnectionFactory connectionFactory)
        {
            this.connectionFactory = connectionFactory;
        }

        public ReadOnlyCollection<Transfer> GetTransfers(string electionEventId, string contestId, string countingEmlAreaContextId)
        {
            return connectionFactory.SP_GetList<Transfer>(
                "Transfer_GetTransfers",
                new
                {
                    ElectionEventId = electionEventId,
                    ContestId = contestId,
                    CountingEmlAreaContextId = countingEmlAreaContextId
                })
                .ToList().AsReadOnly();
        }

        public TransferDetails GetTransferDetails(int transferJobId)
        {
            return connectionFactory.SP_Get<TransferDetails>(
                "Transfer_GetDetails",
                new
                {
                    TransferJobId = transferJobId
                });
        }

        public async Task<ReadOnlyCollection<TransferToCheckForStatus>> GetTransfersEligibleForStatusCheckAsync(int statusCheckExpirationInMinutes)
        {
            var parameters = new
            {
                StatusCheckExpirationInMinutes = statusCheckExpirationInMinutes,
                FileTransferFinishedState = TransferState.FileTransferFinished.Id,
                QueuedOnServerState = TransferState.QueuedOnServer.Id,
                StartedOnServerState = TransferState.StartedOnServer.Id
            };

            var result = await connectionFactory.SP_GetListAsync<TransferToCheckForStatus>("Transfer_GetTransfersToCheckForStatus", parameters).ConfigureAwait(false);
            return result.ToList().AsReadOnly();
        }

        public async Task<ReadOnlyCollection<TransferToCleanUp>> GetTransfersEligibleForCleanupAsync(int cleanupExpirationWindowInMinutes)
        {
            var result = await connectionFactory.SP_GetListAsync<TransferToCleanUp>("Transfer_GetTransfersEligibleForCleanup", new
            {
                ExpirationWindowInMinutes = cleanupExpirationWindowInMinutes,
                FileTransferStartedState = TransferState.FileTransferStarted.Id
            }).ConfigureAwait(false);
            return result.ToList().AsReadOnly();
        }
    }
}
