from datetime import datetime

from flask_security import UserMixin, RoleMixin

from libertywiki.db import Model, Table, Column, ForeignKey, Boolean, DateTime, Integer, String, Text, backref, \
    relationship


roles_users = Table(
    'roles_users',
    Column('role_id', Integer, ForeignKey('roles.id')),
    Column('user_id', Integer, ForeignKey('users.id'))
)


class Page(Model):
    """
    Page model
    """
    __tablename__ = 'pages'

    id = Column(Integer, primary_key=True)
    user_id = Column(Integer, ForeignKey('users.id'))
    title = Column(String(255), nullable=False)
    body = Column(Text)
    slug = Column(String(255), nullable=False, index=True, unique=True)
    created = Column(DateTime, default=datetime.now())
    modified = Column(DateTime, default=datetime.now())

    def __str__(self):
        return '<Page {}>'.format(self.title)


class Role(Model, RoleMixin):
    """
    Role model
    """
    __tablename__ = 'roles'

    id = Column(Integer, primary_key=True)
    name = Column(String(255), unique=True, index=True, nullable=False)
    description = Column(Text)

    def __str__(self):
        return '<Role {}>'.format(self.name)


class User(Model, UserMixin):
    """
    User model
    """
    __tablename__ = 'users'

    id = Column(Integer, primary_key=True)
    name = Column(String(255))
    email = Column(String(255), nullable=False, index=True, unique=True)
    password = Column(String(255), nullable=False)
    activation_code = Column(String(255), index=True)
    active = Column('is_active', Boolean, index=True)
    confirmed_at = Column(DateTime)
    fs_uniquifier = Column(String(255), unique=True, nullable=False, index=True)

    roles = relationship('Role', secondary=roles_users, backref=backref('users', lazy='dynamic'))

    def __str__(self):
        return '<User {}>'.format(self.email)
