from flask import flash, redirect, url_for, request
from flask_login import current_user
from wtforms import BooleanField
from app.utils.priv_required import priv_required
from app.models.users import Member
from app.models.trophies import Trophy
from app.forms.account import AdminUpdateAccountForm, AdminDeleteAccountForm, \
    AdminAccountEditTrophyForm
from app.utils.render import render
from app.utils.notify import notify
from app import app, db
from config import V5Config


@app.route('/admin/account/<user_id>/edit', methods=['GET', 'POST'])
@priv_required('access-admin-panel', 'edit-account')
def adm_edit_account(user_id):
    user = Member.query.filter_by(id=user_id).first_or_404()

    form = AdminUpdateAccountForm(prefix="user")

    class TrophyForm(AdminAccountEditTrophyForm):
        pass

    for t in Trophy.query.all():
        setattr(TrophyForm, f't{t.id}', BooleanField(t.name))
    setattr(TrophyForm, "user_trophies", [f't{t.id}' for t in user.trophies])
    trophy_form = TrophyForm(prefix="trophies")

    if form.submit.data:
        if form.validate_on_submit():
            newname = form.username.data
            names = list(Member.query.filter(Member.id != user.id).values(Member.name))
            if newname in names:
                # TODO: avoid this exception
                # You cannot user vd.name_available because name will always be
                # invalid! Maybe you can add another validator with arguments
                raise Exception(f'{newname} is not available')
            user.update(
                avatar=form.avatar.data or None,
                name=form.username.data or None,
                email=form.email.data or None,
                password=form.password.data or None,
                birthday=form.birthday.data,
                signature=form.signature.data,
                bio=form.biography.data,
                newsletter=form.newsletter.data,
                xp=form.xp.data or None,
            )
            db.session.merge(user)
            db.session.commit()
            # TODO: send an email to member saying his account has been modified
            user.notify(f"Vos informations personnelles ont été modifiées par {current_user.name}.")
            flash('Modifications effectuées', 'ok')
            return redirect(request.url)
        else:
            flash('Erreur lors de la modification', 'error')

    if trophy_form.submit.data:
        if trophy_form.validate_on_submit():
            for id, field in trophy_form.__dict__.items():
                if id[0] == "t":
                    print(f"id: {id[1:]}, name: {field.label}, checked={field.data}", end=" ")
                    if field.data:
                        print(f"Add trophy {id[1:]}")
                        user.add_trophy(int(id[1:]))
                    else:
                        print(f"Del trophy {id[1:]}")
                        user.del_trophy(int(id[1:]))

            db.session.merge(user)
            db.session.commit()
        else:
            flash("Erreur lors de l'ajout du trophée", 'error')

    user_owned = set()
    for t in user.trophies:
        user_owned.add(f"t{t.id}")

    return render('admin/edit_account.html', user=user,
        form=form, trophy_form=trophy_form, user_owned=user_owned)


@app.route('/admin/account/<user_id>/delete', methods=['GET', 'POST'])
@priv_required('access-admin-panel', 'delete-account')
def adm_delete_account(user_id):
    user = Member.query.filter_by(id=user_id).first_or_404()

    # Note: A user deleting their own account will be disconnected.

    # TODO: Add an overview of what will be deleted.
    # * How many posts will be turned into guest posts
    # * Option: purely delete the posts in question
    # * How many PMs will be deleted (can't unassign PMs)
    # * etc.
    del_form = AdminDeleteAccountForm()
    if del_form.submit.data:
        if del_form.validate_on_submit():
            user.delete()
            flash('Compte supprimé', 'ok')
            return redirect(url_for('adm'))
        else:
            flash('Erreur lors de la suppression du compte', 'error')
            del_form.delete.data = False  # Force to tick to delete the account
    return render('admin/delete_account.html', user=user, del_form=del_form)
