from app import app, db
from app.models.post import Post
from app.utils.render import render
from app.utils.check_csrf import check_csrf
from app.forms.forum import CommentEditForm, AnonymousCommentEditForm
from urllib.parse import urlparse
from flask import redirect, url_for, abort, request
from flask_login import login_required, current_user

@app.route('/post/<int:postid>', methods=['GET','POST'])
# TODO: Allow guest edit of posts
@login_required
def edit_post(postid):
    # TODO: Maybe not safe
    referrer = urlparse(request.args.get('r', default = '/', type = str)).path
    print(referrer)

    p = Post.query.filter_by(id=postid).first_or_404()

    # TODO: Check whether privileged user has access to board
    if p.author != current_user and not current_user.priv("edit-posts"):
        abort(403)

    if p.type == "comment":
        form = CommentEditForm()

        if form.validate_on_submit():
            p.text = form.message.data

            if form.submit.data:
                db.session.add(p)
                db.session.commit()

                return redirect(referrer)

        form.message.data = p.text
        return render('forum/edit_comment.html', comment=p, form=form)
    else:
        abort(404)

@app.route('/post/supprimer/<int:postid>', methods=['GET','POST'])
@login_required
@check_csrf
def delete_post(postid):
    p = Post.query.filter_by(id=postid).first_or_404()

    # TODO: Check whether privileged user has access to board
    if p.author != current_user and not current_user.priv("delete-posts"):
        abort(403)

    for a in p.attachments:
        a.delete_file()
        db.session.delete(a)
    db.session.commit()

    db.session.delete(p)
    db.session.commit()
    return redirect(request.referrer)
