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

from app.models.poll import Poll
from app.models.polls.simple import SimplePoll
from app.models.polls.multiple import MultiplePoll
from app.forms.poll import PollForm
from app.utils.render import render


@app.route("/compte/sondages", methods=['GET', 'POST'])
@login_required
def account_polls():
    form = PollForm()
    polls = (Poll.query.filter(Poll.author == current_user)
        .order_by(Poll.end.desc()))
    polls_types = {
        'simplepoll': SimplePoll,
        'multiplepoll': MultiplePoll,
    }

    if form.validate_on_submit():
        choices = list(filter(None, form.choices.data.split('\n')))
        p = polls_types[form.type.data](current_user, form.title.data, choices,
            start=form.start.data, end=form.end.data)
        db.session.add(p)
        db.session.commit()

        flash(f"Le sondage {p.id} a été créé", "info")

    return render("account/polls.html", polls=polls, form=form)
