from flask import redirect, url_for, request, flash
from flask_login import login_user, logout_user, login_required, current_user
from urllib.parse import urlparse, urljoin
from app import app
from app.forms.login import LoginForm
from app.models.users import Member
from app.models.privs import Group
from app.utils.render import render
from config import V5Config


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

    form = LoginForm()
    lateral = LoginForm(prefix="menu_")

    if lateral.validate_on_submit():
        form = lateral
    if form.validate_on_submit():
        member = Member.query.filter_by(name=form.username.data).first()

        # Check if member can login
        if member is not None and "No login" in [g.name for g in member.groups]:
            flash('Cet utilisateur ne peut pas se connecter', 'error')
            if request.referrer:
                return redirect(request.referrer)
            return redirect(url_for('index'))

        # Check if password is ok
        if member is None or not member.check_password(form.password.data):
            flash('Pseudo ou mot de passe invalide', 'error')
            if request.referrer:
                return redirect(request.referrer)
            return redirect(url_for('index'))

        # Login & update time-based trophies
        login_user(member, remember=form.remember_me.data,
                   duration=V5Config.REMEMBER_COOKIE_DURATION)
        member.update_trophies("on-login")

        # Redirect safely (https://huit.re/open-redirect)
        def is_safe_url(target):
            ref_url = urlparse(request.host_url)
            test_url = urlparse(urljoin(request.host_url, target))
            return test_url.scheme in ('http', 'https') and \
                ref_url.netloc == test_url.netloc

        next = request.args.get('next')
        if next and is_safe_url(next):
            return redirect(next)
        if request.referrer:
            return redirect(request.referrer)
        return redirect(url_for('index'))

    return render('account/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'))
