#!/usr/bin/env python

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

import config

Base = declarative_base()


def get_tables(model):
    for i in dir(model):
        var = getattr(model, i)
        if type(var) == type(Base) and var.__module__ == model.__name__:
            # subtables, many to many relations
            for i in dir(var):
                var2 = getattr(var, i)
                if type(var2) == sqlalchemy.schema.Table:
                    yield var2
            yield var


models = ('main.model',
          'plugins.model',
          'user.model',
          'clientjob.model',)

def init_model():
    '''
    returns the needed Base and metadata for defining new classes.
    New classes should inheritance from Base.

    >>> Base, metadata = init_model()
    '''

    base = declarative_base()
    metadata = base.metadata

    return base, metadata


def create_from_model(model, database=config.DB):
    '''
    Create tables defined in a model.
    '''

    metadata = model.metadata
    db = create_engine(database, echo=False)
    for table in get_tables(model):
        if type(table) == sqlalchemy.schema.Table:
            t = table
        else:
            print "creating table %s" % table.__tablename__
            t = metadata.tables[table.__tablename__]
        t.create(bind=db, checkfirst=True)


def drop_from_model(model, database=config.DB):
    '''
    Drop tables defined in a model.
    '''

    metadata = model.metadata
    s = connect()

    for table in get_tables(model):
        if type(table) == sqlalchemy.schema.Table:
            continue
        for i in s.query(table).all():
            s.delete(i)

    for table in get_tables(model):
        if type(table) == sqlalchemy.schema.Table:
            t = table
        else:
            print "dropping table %s" % table.__tablename__
            t = metadata.tables[table.__tablename__]
        t.drop(bind=s.bind, checkfirst=True)
    s.commit()


def connect(database=config.DB):
    db = create_engine(database, echo=False)
    session = scoped_session(sessionmaker(bind=db))
    return session


def create(database=config.DB):
    print config.DB
    db = create_engine(database, echo=False)
    for model in models:
        m = __import__(model, fromlist=["true"])
        m.metadata.create_all(db)


if __name__ == '__main__':
    create()
