import datetime

from flask_security import RoleMixin, UserMixin
from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

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


class Roles(db.Model, RoleMixin):
    __tablename__ = "roles"
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(80), unique=True)
    description = db.Column(db.String(255))

    def __str__(self):
        return self.name


class Modules(db.Model):
    __tablename__ = "modules"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(100))
    versions = db.relationship('ModuleVersions', backref='modules', lazy=True)


class ModuleVersions(db.Model):
    __tablename__ = "moduleversions"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    version = db.Column(db.String(10))
    module_id = db.Column(db.Integer, db.ForeignKey('modules.id'), nullable=False)


class Users(db.Model, UserMixin):
    __tablename__ = "users"
    id = db.Column(db.Integer, primary_key=True)
    date_created = db.Column(db.DateTime, default=datetime.datetime.utcnow)
    username = db.Column(db.String(100))
    email = db.Column(db.String(100), unique=True)
    password = db.Column(db.String(200))
    active = db.Column(db.Boolean)
    roles = db.relationship('Roles', secondary=roles_users,
                            backref=db.backref('users', lazy='dynamic'))

    def __repr__(self):
        return str(self.username)

    def __str__(self):
        return str(self.username)
