from flask import redirect, url_for, request, flash
from flask_login import login_user, logout_user, login_required, current_user
from app import app
from app.forms.login import LoginForm
from app.models.users import Member
from app.utils.render import render


@app.route('/login', methods=['GET', 'POST'])
def login():
    if current_user.is_authenticated:
        return redirect(url_for('index'))

    form = LoginForm()
    if form.validate_on_submit():
        member = Member.query.filter_by(name=form.username.data).first()
        if member is None or not member.check_password(form.password.data):
            flash('Pseudo ou mot de passe invalide', 'error')
            return redirect(request.referrer)
        login_user(member, remember=form.remember_me.data)
        # TODO: est-ce qu'on garde ce foutu message plus chiant qu'autre chose ?
        flash(f'Bon retour parmi nous, {current_user.name} !', 'info')
        if request.args.get('next'):
            return redirect(request.args.get('next'))
        if request.referrer:
            return redirect(request.referrer)
        return redirect(url_for('index'))
    return render('login.html', form=form)


@app.route('/logout')
@login_required
def logout():
    try:
        print(request.referrer)
    except Exception as e:
        print('No referrer:', e)

    logout_user()
    flash('Déconnexion réussie', 'info')
    if request.referrer:
        return redirect(request.referrer)
    return redirect(url_for('index'))
