using System;
using System.Transactions;
using Valg.EVA.Skanning.Contracts;

namespace Valg.EVA.Skanning.Entity.SqlConnection
{
    public class TransactionScopeFactory
    {
        private readonly IDatabaseConfiguration databaseConfiguration;

        public TransactionScopeFactory(IDatabaseConfiguration databaseConfiguration)
        {
            this.databaseConfiguration = databaseConfiguration;
        }

        public TransactionScope GetTransactionScope(int timeOutInSeconds = 60)
        {
            var isTimeoutOverriddenInConfigFile = databaseConfiguration.OverrideTimeOut;
            if (isTimeoutOverriddenInConfigFile)
            {
                timeOutInSeconds = databaseConfiguration.TransactionTimeOut;
            }

            return new TransactionScope(TransactionScopeOption.Required, new TransactionOptions
            {
                Timeout = new TimeSpan(0, 0, timeOutInSeconds),
                IsolationLevel = IsolationLevel.ReadCommitted
            }, 
            TransactionScopeAsyncFlowOption.Enabled);
        }
    }
}
