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

namespace RDH.PharmacyPlatform.Sync.Core
{
    internal class ConnectionSessionFactory
    {
        private static Object _lock;
        private static Dictionary<Int32, IDbConnection> _cachedConnectionSessions;
        private ConnectionSessionFactory() 
        {   
        }
        static ConnectionSessionFactory() 
        {
            _lock = new object();
            _cachedConnectionSessions = new Dictionary<int, IDbConnection>();
        }
        public static IDbConnection CreateConnection(String connString) 
        {
            //Debug.WriteLine($"CreateConnection start, tid:{Thread.CurrentThread.ManagedThreadId}");
            IDbConnection connection = null;
            lock (_lock)
            {
                if (_cachedConnectionSessions.ContainsKey(Thread.CurrentThread.ManagedThreadId)) 
                {
                    connection = _cachedConnectionSessions[Thread.CurrentThread.ManagedThreadId];
                }
                else 
                {
                    connection = new SQLiteConnection();
                    _cachedConnectionSessions.Add(Thread.CurrentThread.ManagedThreadId, connection);
                    connection.ConnectionString = connString;
                    connection.Open();
                }
            }
            //Debug.WriteLine("CreateConnection end");
            return connection;
        }
        public static IDbConnection GetConnection() 
        {
            //Debug.WriteLine($"GetConnection start, tid:{Thread.CurrentThread.ManagedThreadId}");
            IDbConnection conn = null;
            lock (_lock) 
            {
                if (_cachedConnectionSessions.ContainsKey(Thread.CurrentThread.ManagedThreadId))
                {
                    conn = _cachedConnectionSessions[Thread.CurrentThread.ManagedThreadId];
                }
            }
            return conn;
        }
        public static void CloseConnection() 
        {
            //Debug.WriteLine($"CloseConnection start, tid:{Thread.CurrentThread.ManagedThreadId}");
            lock (_lock)
            {
                if (_cachedConnectionSessions.ContainsKey(Thread.CurrentThread.ManagedThreadId))
                {
                    IDbConnection conn = _cachedConnectionSessions[Thread.CurrentThread.ManagedThreadId];
                    conn.Close();
                    conn.Dispose();
                    _cachedConnectionSessions.Remove(Thread.CurrentThread.ManagedThreadId);
                }
            }
        }
    }
}
