from flask import redirect, url_for, request, flash
from flask_login import login_required, current_user, logout_user
from app import app, db
from app.forms.account import UpdateAccountForm, RegistrationForm, DeleteAccountForm
from app.models.users import Member
from app.utils.render import render
import app.utils.ldap as ldap
from config import V5Config


@app.route('/account', methods=['GET', 'POST'])
@login_required
def edit_account():
    form = UpdateAccountForm()
    if form.submit.data:
        if form.validate_on_submit():
            current_user.update(
                avatar=form.avatar.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
            )
            db.session.merge(current_user)
            db.session.commit()
            current_user.update_trophies("on-profile-update")
            flash('Modifications effectuées', 'ok')
            return redirect(request.url)
        else:
            flash('Erreur lors de la modification', 'error')

    return render('account/account.html', form=form)


@app.route('/account/delete', methods=['GET', 'POST'])
@login_required
def delete_account():
    del_form = DeleteAccountForm()
    if del_form.submit.data:
        if del_form.validate_on_submit():
            db.session.delete(current_user)
            logout_user()
            db.session.commit()
            flash('Compte supprimé', 'ok')
            return redirect(url_for('index'))
        else:
            flash('Erreur lors de la suppression du compte', 'error')
            del_form.delete.data = False  # Force to tick to delete the account
    return render('account/delete_account.html', del_form=del_form)


@app.route('/register', methods=['GET', 'POST'])
def register():
    if current_user.is_authenticated:
        return redirect(url_for('index'))
    form = RegistrationForm()
    if form.validate_on_submit():
        member = Member(form.username.data, form.email.data, form.password.data)
        member.newsletter = form.newsletter.data
        db.session.add(member)
        db.session.commit()
        # Workflow with LDAP is User → Postgresql → LDAP → Change password
        if V5Config.USE_LDAP:
            ldap.add_member(member)
            ldap.set_password(member, form.password.data)
        flash('Inscription réussie', 'ok')
        return redirect(url_for('validation') + "?email=" + form.email.data)
    return render('account/register.html', title='Register', form=form)


@app.route('/register/validation/', methods=['GET', 'POST'])
def validation():
    mail = request.args['email']
    if current_user.is_authenticated:
        return redirect(url_for('index'))
    return render('account/validation.html', mail=mail)
