from app import db
from sqlalchemy.types import Integer, Text, DateTime
from sqlalchemy.schema import Column
from hashlib import md5
from sqlalchemy.ext.declarative import declarative_base


class _Base(object):
    query = db.session.query_property()


Base = declarative_base(cls=_Base)


followers = db.Table(
    'followers',
    Base.metadata,
    Column('follower_id', Integer, db.ForeignKey('user.id')),
    Column('followed_id', Integer, db.ForeignKey('user.id'))
)


class User(Base):
    __tablename__ = 'user'
    __searchable__ = ['nickname']

    id = Column(Integer, primary_key=True)
    nickname = Column(Text, index=True, unique=True)
    email = Column(Text, index=True, unique=True)
    about_me = Column(Text)
    last_seen = Column(DateTime)
    posts = db.relationship('Post', backref='author', lazy='dynamic')
    followed = db.relationship('User',
                               secondary=followers,
                               primaryjoin=(followers.c.follower_id == id),
                               secondaryjoin=(followers.c.followed_id == id),
                               backref=db.backref('followers', lazy='dynamic'),
                               lazy='dynamic')

    @property
    def is_authenticated(self):
        return True

    @property
    def is_active(self):
        return True

    @property
    def is_anonymous(self):
        return False

    def get_id(self):
        return str(self.id)

    def __repr__(self):
        return '<User %r>' % self.nickname

    @classmethod
    def get(cls, id):
        try:
            return cls.query.get(id)
        except KeyError:
            return None

    def avatar(self, size):
        return 'http://www.gravatar.com/avatar/{avatar}?d=mm&s={size}'.format(
            avatar=md5(self.email.encode('utf-8')).hexdigest(),
            size=size
        )

    @staticmethod
    def make_unique_nickname(nickname):
        if User.query.filter_by(nickname=nickname).first() is None:
            return nickname
        version = 2
        while True:
            new_nickname = nickname + str(version)
            if User.query.filter_by(nickname=new_nickname).first() is None:
                break
            version += 1
        return new_nickname

    def follow(self, user):
        if not self.is_following(user):
            self.followed.append(user)
            return self

    def unfollow(self, user):
        if self.is_following(user):
            self.followed.remove(user)
            return self

    def is_following(self, user):
        return self.followed.filter(followers.c.followed_id == user.id).count() > 0

    def followed_posts(self):
        return (
            Post
            .query
            .join(
                followers, (followers.c.followed_id == Post.user_id)    # Join table, Join condition
            ).filter(
                followers.c.follower_id == self.id
            )
            .order_by(
                Post.timestamp.desc()
            )
        )


class Post(Base):
    __tablename__ = 'post'
    __searchable__ = ['body']   # Searchable columns

    id = Column(Integer, primary_key=True)
    body = Column(Text)
    timestamp = Column(DateTime)
    user_id = Column(Integer, db.ForeignKey('user.id'))

    def __repr__(self):
        return '{0}(body={1})'.format(self.__class__.__name__, self.body)
