from flask import url_for
from flask_migrate import Migrate, MigrateCommand
from flask_script import Manager

from PDMI import server, db, Roles, Users

server.config.from_object('PDMI.config')

migrate = Migrate(server, db)
manager = Manager(server)

manager.add_command('db', MigrateCommand)

@manager.option('-m', '--mail', help="Mail de l'utilisateur à mettre en admin")
def set_superadmin(mail):
    roles = Roles.query.filter(Roles.name == "superadmin").all()
    if len(roles) == 0:
        superAdminRole = Roles(name="superadmin", description="Role pour les super administrateurs")
        db.session.add(superAdminRole)
        db.session.commit()
    role = Roles.query.filter(Roles.name == "superadmin").first()
    users = Users.query.filter(Users.email == mail).all()
    if len(users) == 0:
        print("Aucun compte avec le mail {mail} existe, annulation".format(mail=mail))
        return
    user = Users.query.filter(Users.email == mail).first()
    user.roles.append(role)
    db.session.commit()
    print("Role ajouté")

@manager.command
def list_routes():
    import urllib.parse
    output = []
    for rule in server.url_map.iter_rules():
        options = {}
        for arg in rule.arguments:
            if arg == "id":
                options[arg] = "0"
            else:
                options[arg] = f"[{arg}]"
        methods = ",".join(rule.methods)
        url = url_for(rule.endpoint, **options)
        line = urllib.parse.unquote("{:50s} {:20s} {}".format(rule.endpoint, methods, url))
        output.append(line)
    for line in sorted(output):
        print(line)


if __name__ == '__main__':
    manager.run()
