#
# See LICENCE for detail
# Copyright (c) 2014 IRI
#

from sqlalchemy import create_engine, MetaData
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base

import psycopg2.extras

from twisted.python import log

from txpostgres.txpostgres import Connection, ConnectionPool

import config


engine = create_engine(config.CONN_STR, convert_unicode=True)
db_session = scoped_session(sessionmaker(autocommit=False,
                                         autoflush=False,
                                         bind=engine))

Base = declarative_base()
Base.query = db_session.query_property()

def init_db():
    # import all modules here that might define models so that
    # they will be registered properly on the metadata.  Otherwise
    # you will have to import them first before calling init_db()
    import models
    Base.metadata.create_all(bind=engine)


class DictConnection(Connection):

    @staticmethod
    def connectionFactory(*args, **kwargs):
        kwargs['connection_factory'] = psycopg2.extras.DictConnection
        return psycopg2.connect(*args, **kwargs)


class DictConnectionPool(ConnectionPool):
    connectionFactory = DictConnection


def create_connection_pool(conn_string):

    created_connection_pool = DictConnectionPool(None, conn_string)

    d = created_connection_pool.start()
    d.addErrback(log.err)

    return created_connection_pool, d
