﻿using System;
using System.Configuration;
using System.Linq;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using NHibernate.Tool.hbm2ddl;
using Configuration = NHibernate.Cfg.Configuration;

namespace Slackbot.Kamisama.NHibernate
{
  public class Fabric
  {
    private static readonly Lazy<ISessionFactory> Factory = new Lazy<ISessionFactory>(() => CreateFactoryImpl());

    public static Func<ISessionFactory> CreateFactoryImpl = CreateFactory;

    public static ISession OpenSession()
    {
      var session = Factory.Value.OpenSession();
      session.FlushMode = FlushMode.Commit;
      return session;
    }

    private static ISessionFactory CreateFactory()
    {
      var connectionString = ConfigurationManager.ConnectionStrings.OfType<ConnectionStringSettings>()
        .Single(c => c.Name == "nhibernate").ConnectionString;
      return Fluently
        .Configure()
        .Database(MsSqlConfiguration.MsSql2008.ConnectionString(connectionString))
        .Mappings(m => m.FluentMappings.AddFromAssemblyOf<Fabric>())
        .ExposeConfiguration(BuildSchema)
        .BuildSessionFactory();
    }

    private static void BuildSchema(Configuration config)
    {
      new SchemaUpdate(config).Execute(false, true);
    }

  }
}