from flask_login import login_required
from flask_wtf import FlaskForm
from wtforms import SubmitField
from app.models.users import Member, Group, GroupPrivilege
from app.models.privs import SpecialPrivilege
from app.utils.render import render
from app.utils.priv_required import priv_required
from app import app, db

@app.route('/admin', methods=['GET', 'POST'])
@priv_required('panel-admin')
def admin():
    class AdminForm(FlaskForm):
        submit = SubmitField('Régénérer les groupes, les privilèges, et les ' +
            'membres de test "PlanèteCasio" et "GLaDOS" (mdp "v5-forever")')

    form = AdminForm()
    if form.validate_on_submit():
        # Clean up groups
        for g in Group.query.all():
            db.session.delete(g)
        db.session.commit( )

        # Create base groups
        g_admins    = Group('Administrateur', 'color: red')
        g_modos     = Group('Modérateur', 'color: green')
        g_redacs    = Group('Rédacteur', 'color: blue')
        g_community = Group('Compte communautaire', 'background: #c8c8c8;' +
          'border-radius: 4px; color: #303030; padding: 1px 2px')
        db.session.add(g_admins)
        db.session.add(g_modos)
        db.session.add(g_redacs)
        db.session.add(g_community)

        # Clean up test members
        for name in "PlanèteCasio GLaDOS".split():
            m = Member.query.filter_by(name=name).first()
            if m is not None:
                db.session.delete(m)
            db.session.commit()

        # Create template members
        m = Member('PlanèteCasio','contact@planet-casio.com','v5-forever')
        m.groups.append(g_community)
        db.session.add(m)

        m = Member('GLaDOS', 'glados@aperture.science', 'v5-forever')
        m.groups.append(g_modos)
        m.groups.append(g_redacs)
        db.session.add(m)
        db.session.add(SpecialPrivilege(m, "edit-posts"))
        db.session.add(SpecialPrivilege(m, "shoutbox-ban"))

        db.session.commit()

    users  = Member.query.all()
    groups = Group.query.all()
    return render('admin.html', users=users, groups=groups, form=form)
