from app import app, db
from flask import abort, flash, redirect, request, url_for
from flask_login import current_user
from app.utils.render import render
from app.models.poll import Poll
from app.forms.poll import DeletePollForm

@app.route("/sondages/<int:poll_id>/supprimer", methods=['GET', 'POST'])
def poll_delete(poll_id):
    poll = Poll.query.get(poll_id)
    if poll is None:
        abort(404)

    if current_user != poll.author and \
        not current_user.priv('delete-posts'):
        abort(403)

    form = DeletePollForm()

    if form.validate_on_submit():
        poll.delete()
        db.session.commit()

        flash('Le sondage a été supprimé', 'info')
        return redirect(url_for('account_polls'))

    return render('poll/delete.html', poll=poll, del_form=form)
