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


@app.route('/account', methods=['GET', 'POST'])
@login_required
def edit_account():
    form = UpdateAccountForm()
    if request.method == "POST":
        if form.validate_on_submit():
            if form.avatar.data:
                f = form.avatar.data
                f.save("./app/static/" + current_user.avatar)
            current_user.update(
                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()
            flash('Modifications effectuées', 'ok')
        else:
            flash('Erreur lors de la modification', 'error')

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


@app.route('/account/delete', methods=['GET', 'POST'])
@login_required
def delete_account():
    del_form = DeleteAccountForm()
    if request.method == "POST":
        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('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)
        db.session.add(member)
        db.session.commit()
        flash('Inscription réussie', 'ok')
        return redirect(url_for('validation'))
    return render('register.html', title='Register', form=form)


@app.route('/register/validation/')
def validation():
    if current_user.is_authenticated:
        return redirect(url_for('index'))
    return render('validation.html')
