using NHibernate;
using NHibernate.Cfg;
using System.Collections.Generic;

namespace AidA.Data
{
    public sealed class HibernateHelper
    {
        private static ISession CurrentSession;
        private static ISessionFactory SessionFactory;

        private static string ConnectString;

        static HibernateHelper()
        {
        }

        public static ISession GetCurrentSession()
        {
            if (CurrentSession == null)
            {
                CurrentSession = SessionFactory.OpenSession();
            }

            return CurrentSession;
        }

        public static void CloseSession()
        {
            if (CurrentSession == null)
            {
                // No current session
                return;
            }

            CurrentSession.Close();
        }

        public static void CloseSessionFactory()
        {
            if (SessionFactory != null)
            {
                SessionFactory.Close();
            }
        }

        public static string GetConnectString()
        {
            return ConnectString;
        }

        public static void Connect(string databaseUserName, string password)
        {
            Configuration configuration = new Configuration().Configure();

            IDictionary<string, string> properties = configuration.Properties;
            ConnectString = new Configuration().Configure().GetProperty("connection.connection_string");
            ConnectString = ConnectString.Replace("userId", databaseUserName);
            ConnectString = ConnectString.Replace("userPwd", password);
            configuration.SetProperty("connection.connection_string", ConnectString);

            SessionFactory = configuration.BuildSessionFactory();
        }
    }
}