from app import app, db
from app.models.program import Program
from app.models.thread import Thread
from app.models.comment import Comment
from app.models.tag import Tag
from app.models.attachment import Attachment
from app.utils.render import render
from app.forms.programs import ProgramCreationForm

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

@app.route('/programmes/soumettre', methods=['GET', 'POST'])
@login_required
def program_submit():

    form = ProgramCreationForm()
    if form.validate_on_submit():
        # First create a new thread
        # TODO: Reuse a thread when performing topic promotion
        th = Thread()
        db.session.add(th)
        db.session.commit()

        # Create its top comment
        c = Comment(current_user, form.message.data, th)
        db.session.add(c)
        db.session.commit()
        th.set_top_comment(c)
        db.session.merge(th)

        # Then build the actual program
        p = Program(current_user, form.name.data, th)
        db.session.add(p)
        db.session.commit()

        # Add tags
        for tag in form.tags.selected_tags():
            db.session.add(Tag(p, tag))
        db.session.commit()

        # Manage files
        attachments = []
        for file in form.attachments.data:
            if file.filename != "":
                a = Attachment(file, c)
                attachments.append((a, file))
                db.session.add(a)
        db.session.commit()
        for a, file in attachments:
            a.set_file(file)

        current_user.add_xp(20)
        current_user.update_trophies('new-program')

        flash('Le programme a bien été soumis', 'ok')
        return redirect(url_for('program_index'))

    return render('/programs/submit.html', form=form)
