from app import app, db
from app.models.user import Guest
from app.models.program import Program
from app.models.comment import Comment
from app.models.thread import Thread
from app.utils.render import render
from app.forms.forum import CommentForm, AnonymousCommentForm
from config import V5Config

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

@app.route('/programmes/<programpage:page>', methods=['GET','POST'])
def program_view(page):
    p, page = page

    if current_user.is_authenticated:
        form = CommentForm()
    else:
        form = AnonymousCommentForm()

    if form.validate_on_submit() and (
        V5Config.ENABLE_GUEST_POST or current_user.is_authenticated):

        # Manage author
        if current_user.is_authenticated:
            author = current_user
        else:
            author = Guest(form.pseudo.data)
            db.session.add(author)

        # Create comment
        c = Comment(author, form.message.data, p.thread)
        db.session.add(c)
        db.session.commit()
        c.create_attachments(form.attachments.data)

        # Update member's xp and trophies
        if current_user.is_authenticated:
            current_user.add_xp(1)
            current_user.update_trophies('new-post')

        flash('Message envoyé', 'ok')
        # Redirect to empty the form
        return redirect(url_for('program_view', page=(p, "fin"), _anchor=c.id))

    if page == -1:
        page = (p.thread.comments.count() - 1) // Thread.COMMENTS_PER_PAGE + 1

    comments = p.thread.comments.order_by(Comment.date_created.asc()) \
        .paginate(page, Thread.COMMENTS_PER_PAGE, True)

    return render('/programs/program.html', p=p, form=form, comments=comments)
