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

from app import app, db
from config import V5Config
from app.utils.render import render
from app.forms.forum import CommentForm
from app.models.forum import Forum
from app.models.topic import Topic
from app.models.thread import Thread
from app.models.comment import Comment


@app.route('/forum/<forum:f>/<topicslug:t>', methods=['GET', 'POST'])
def forum_topic(f, t):
    # Quick n' dirty workaround to converters
    if f != t.forum:
        abort(404)

    form = CommentForm()

    if form.validate_on_submit():
        c = Comment(current_user, form.message.data, t.thread)
        db.session.add(c)
        db.session.commit()

        # Update member's xp
        current_user.add_xp(V5Config.XP_POINTS['comment'])
        db.session.merge(current_user)
        db.session.commit()

        flash('Message envoyé', 'ok')
        # Redirect to empty the form
        return redirect(url_for('forum_topic', f=f, t=t))

    # Update views
    t.views += 1
    db.session.merge(t)
    db.session.commit()

    if request.args.get('page') == "last":
        page = t.thread.comments.count() // V5Config.COMMENTS_PER_PAGE + 1
    else:
        page = request.args.get('page', 1, type=int)

    comments = t.thread.comments.paginate(page,
        V5Config.COMMENTS_PER_PAGE, True)

    return render('/forum/topic.html', t=t, form=form, comments=comments)
