from flask import request, flash, redirect, url_for
from app.utils.priv_required import priv_required
from app.models.trophies import Trophy, Title
from app.forms.trophies import TrophyForm, DeleteTrophyForm
from app.utils.render import render
from app import app, db


@app.route('/admin/trophies', methods=['GET', 'POST'])
@priv_required('access-admin-panel', 'edit-trophies')
def adm_trophies():
    form = TrophyForm()
    if request.method == "POST":
        if form.validate_on_submit():
            is_title = form.title.data
            if is_title:
                trophy = Title(form.name.data, form.css.data)
            else:
                trophy = Trophy(form.name.data)
            db.session.add(trophy)
            db.session.commit()
            flash(f'Nouveau {["trophée", "titre"][is_title]} ajouté', 'ok')
        else:
            flash('Erreur lors de la création du trophée', 'error')

    trophies = Trophy.query.all()
    return render('admin/trophies.html', trophies=trophies,
        form=form)


@app.route('/admin/trophies/<trophy_id>/edit', methods=['GET', 'POST'])
@priv_required('access-admin-panel', 'edit-trophies')
def adm_edit_trophy(trophy_id):
    trophy = Trophy.query.filter_by(id=trophy_id).first_or_404()

    form = TrophyForm()
    if request.method == "POST":
        if form.validate_on_submit():
            is_title = form.title.data != ""
            if is_title:
                trophy.name = form.name.data
                trophy.title = form.title.data
                trophy.css = form.css.data
            else:
                trophy.name = form.name.data
            db.session.merge(trophy)
            db.session.commit()
            flash(f'{["Trophée", "Titre"][is_title]} modifié', 'ok')
            return redirect(url_for('adm_trophies'))
        else:
            flash('Erreur lors de la création du trophée', 'error')
    return render('admin/edit_trophy.html', trophy=trophy, form=form)


@app.route('/admin/trophies/<trophy_id>/delete', methods=['GET', 'POST'])
@priv_required('access-admin-panel', 'edit-trophies')
def adm_delete_trophy(trophy_id):
    trophy = Trophy.query.filter_by(id=trophy_id).first_or_404()

    # TODO: Add an overview of what will be deleted.
    del_form = DeleteTrophyForm()
    if request.method == "POST":
        if del_form.validate_on_submit():
            # TODO: Remove relationship with users that have the trophy
            db.session.delete(trophy)
            db.session.commit()
            flash('Trophée supprimé', 'ok')
            return redirect(url_for('adm_trophies'))
        else:
            flash('Erreur lors de la suppression du trophée', 'error')
            del_form.delete.data = False  # Force to tick to delete the trophy
    return render('admin/delete_trophy.html', trophy=trophy, del_form=del_form)
