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

from app import app, db
from config import V5Config
from app.utils.render import render
from app.forms.forum import TopicCreationForm
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/')
def forum_index():
    return render('/forum/index.html')

@app.route('/forum/<forum:f>/', methods=['GET', 'POST'])
def forum_page(f):
    form = TopicCreationForm()

    if form.validate_on_submit():
        # TODO: Check user privileges for this specific forum!

        # First create the thread, then the comment, then the topic
        th = Thread()
        db.session.add(th)
        db.session.commit()

        c = Comment(current_user, form.message.data, th)
        db.session.add(c)
        db.session.commit()

        th.set_top_comment(c)
        db.session.merge(th)

        t = Topic(f, current_user, form.title.data, th)
        db.session.add(t)
        db.session.commit()

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

        flash('Le sujet a bien été créé', 'ok')
        return redirect(url_for('forum_topic', f=f, t=t))

    return render('/forum/forum.html', f=f, form=form)
