
from flask import Flask, render_template, flash, redirect
from flask_sqlalchemy import SQLAlchemy # sudo apt-get install flask_sqlaclhemy
from flask_wtf import FlaskForm
from wtforms.ext.sqlalchemy.orm import model_form

app = Flask(__name__)
db = SQLAlchemy(app)
app.secret_key="ra9ialoH3peNisai5sie8phei2gier7E"

class Comment(db.Model):
        id = db.Column(db.Integer, primary_key=True)
        text = db.Column(db.String, nullable=False)
        name = db.Column(db.String, nullable=False)

CommentForm = model_form(model=Comment, base_class=FlaskForm, db_session=db.session)

@app.before_first_request
def comments():
        db.create_all()

        comment = Comment(text="a comment", name="commenter")
        db.session.add(comment)

        comment = Comment(text="a comment2", name="commenter2")
        db.session.add(comment)

        comment = Comment(text="thing", name="Erkki Esimerkki")
        db.session.add(comment)

        db.session.commit()

@app.route("/new", methods=["GET", "POST"])
def lomake():
	form = CommentForm()
	if form.validate_on_submit():
		comment = Comment()
		form.populate_obj(comment)
		db.session.add(comment)
		db.session.commit()
		flash("Added")
		return redirect("/")
		print("Added your comment, thanks.")

	return render_template("new.html", form=form)

@app.route("/")
def index():
        comments = Comment.query.all()
        return render_template("base.html", comments=comments)

if __name__ == "__main__":
        app.run()
