from sqlalchemy.ext.declarative import declarative_base

from .search import search_query
from skylines import db


class _BaseClass(object):
    @classmethod
    def query(cls, **kw):
        q = db.session.query(cls)

        if kw:
            q = q.filter_by(**kw)

        return q

    @classmethod
    def get(cls, id):
        return cls.query().get(id)

    search_query = classmethod(search_query)


# Base class for all of our model classes: By default, the data model is
# defined with SQLAlchemy's declarative extension, but if you need more
# control, you can switch to the traditional method.
DeclarativeBase = declarative_base(cls=_BaseClass)

# There are two convenient ways for you to spare some typing.
# You can have a query property on all your model classes by doing this:
# DeclarativeBase.query = db.session.query_property()
# Or you can use a session-aware mapper as it was used in TurboGears 1:
# DeclarativeBase = declarative_base(mapper=db.session.mapper)

# Global metadata.
# The default metadata is the one from the declarative base.
metadata = DeclarativeBase.metadata

from .search import search_query
from skylines import db


def query(cls, **kw):
    q = db.session.query(cls)

    if kw:
        q = q.filter_by(**kw)

    return q


def get(cls, id):
    return cls.query().get(id)


DeclarativeBase = db.Model
DeclarativeBase.flask_query = DeclarativeBase.query
DeclarativeBase.query = classmethod(query)
DeclarativeBase.get = classmethod(get)
DeclarativeBase.search_query = classmethod(search_query)

metadata = db.metadata

Use Flask-SQLAlchemy declarative base