using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.Common;
using System.Data.SQLite;

namespace RDH.PharmacyPlatform.Sync.Core
{
    internal class ConnectionSessionScope : IDisposable
    {
        private IDbTransaction _currentTransaction;
        public ConnectionSessionScope(String connectionString)
        {
            IDbConnection conn = ConnectionSessionFactory.CreateConnection(connectionString);
            if (conn != null && conn.State != ConnectionState.Open)
            {
                conn.Open();
            }
        }
        public virtual void Dispose() 
        {
            ConnectionSessionFactory.CloseConnection();
        }
        public IDbTransaction BeginTransaction() 
        {
            if (_currentTransaction != null) 
            {
                return _currentTransaction;
            }
            IDbConnection conn = ConnectionSessionFactory.GetConnection();
            if (conn != null && conn.State == ConnectionState.Open)
            {
                _currentTransaction = conn.BeginTransaction();
                return _currentTransaction;
            }
            return null;
        }
        public void CommitTransaction() 
        {
            if (_currentTransaction != null) 
            {
                _currentTransaction.Commit();
            }
        }
    }
}
