from app import app, db
from flask import abort, flash, redirect, request, url_for
from flask_login import current_user

from app.models.poll import Poll

@app.route("/sondages/<int:poll_id>/voter", methods=['POST'])
def poll_vote(poll_id):
    poll = Poll.query.get(poll_id)

    if poll is None:
        abort(404)
    if not current_user.is_authenticated:
        flash("Seuls les membres connectés peuvent voter", 'error')
        abort(401)
    if not poll.can_vote(current_user):
        flash("Vous n'avez pas le droit de voter", 'error')
        abort(403)
    if poll.has_voted(current_user):
        flash("Vous avez déjà voté", 'error')
        abort(403)
    if not poll.started:
        flash("Le sondage n'a pas débuté", 'error')
        abort(403)
    if poll.ended:
        flash("Le sondage est terminé", 'error')
        abort(403)

    answer = poll.vote(current_user, request)

    if answer is None:
        abort(400)

    db.session.add(answer)
    db.session.commit()

    flash('Le vote a été pris en compte', 'info')

    if request.referrer:
        return redirect(request.referrer)
    return redirect(url_for('index'))
