"""
Routes and views for the flask application.
"""

from datetime import datetime
from flask import render_template, request, session, redirect, url_for, g, flash
from flask_app import app
from functools import wraps

def login_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if 'username' in session:
            return f(*args, **kwargs)
        session['redirect_page'] = request.url
        return redirect(url_for('login'))
    
    return decorated_function


@app.route('/')
@login_required
def home():
    """Renders the home page."""
    return render_template(
        'index.html',
        title = 'Hjem',
        year = datetime.now().year,
        app_name = app.config['APP_NAME']
    )


@app.route('/kontakt')
@login_required
def contact():
    """Renders the contact page."""
    return render_template(
        'contact.html',
        title = 'Kontakt',
        year = datetime.now().year,
        message = 'Your contact page.',
        app_name = app.config['APP_NAME']
    )


@app.route('/login', methods=['GET', 'POST'])
def login():
    """ Login page """
    if 'username' in session:
        # If user is already logged in, redirect to home
        return redirect(url_for('home'))
    
    if request.method == 'POST':
        #processLogin()
        session['username'] = request.form.get('username', None)
        return redirect( session.pop('redirect_page', url_for('home')) )
    
    return render_template(
        'login.html',
        title = 'Logg inn',
        year = datetime.now().year,
        app_name = app.config['APP_NAME']
    )

@app.route('/logout')
def logout():
    session.pop('username', None)
    return redirect(url_for('login'))

@app.route('/database', methods=['GET', 'POST'])
@login_required
def database():
    """ Test page for database """

    cur = g.db.execute("select title, time, participants from meetings order by id desc")
    meetings = [dict(title=row[0], time=row[1], participants=row[2]) for row in cur.fetchall()]
    return render_template('database.html',
                           meetings=meetings,
                           title = 'Database test',
                           year = datetime.now().year,
                           app_name = app.config['APP_NAME']
                           )


@app.route('/add_meeting', methods=['POST'])
@login_required
def add_meeting():
    g.db.execute("insert into meetings (title, time, participants, map_id, creator) VALUES (?, ?, ?, ?, ?)",
                 [request.form['title'], request.form['time'], request.form['participants'], request.form['map_id'], 'kari'])
    g.db.commit()
    flash('Nytt mote lagt til!')
    return redirect(url_for('database'))

@@ -156,16 +156,117 @@
 g, flash
+%0A%0Afrom flask.ext.app.alchemy_database import engine%0Afrom flask.ext.app.alchemy_schema import meetings
 %0Afrom fl
@@ -313,16 +313,17 @@
  wraps%0A%0A
+%0A
 def logi
@@ -553,28 +553,24 @@
 r('login'))%0A
-    
 %0A    return 
@@ -730,19 +730,17 @@
    title
- = 
+=
 'Hjem',%0A
@@ -743,35 +743,33 @@
 m',%0A        year
- = 
+=
 datetime.now().y
@@ -781,35 +781,33 @@
         app_name
- = 
+=
 app.config%5B'APP_
@@ -976,19 +976,17 @@
    title
- = 
+=
 'Kontakt
@@ -992,35 +992,33 @@
 t',%0A        year
- = 
+=
 datetime.now().y
@@ -1037,19 +1037,17 @@
  message
- = 
+=
 'Your co
@@ -1068,35 +1068,33 @@
         app_name
- = 
+=
 app.config%5B'APP_
@@ -1318,20 +1318,16 @@
 home'))%0A
-    
 %0A    if 
@@ -1361,16 +1361,17 @@
        #
+ 
 processL
@@ -1466,17 +1466,16 @@
 edirect(
- 
 session.
@@ -1515,15 +1515,10 @@
 e'))
- 
 )%0A
-    
 %0A   
@@ -1577,19 +1577,17 @@
    title
- = 
+=
 'Logg in
@@ -1594,35 +1594,33 @@
 n',%0A        year
- = 
+=
 datetime.now().y
@@ -1632,35 +1632,33 @@
         app_name
- = 
+=
 app.config%5B'APP_
@@ -1671,16 +1671,17 @@
 %0A    )%0A%0A
+%0A
 @app.rou
@@ -1781,16 +1781,17 @@
 gin'))%0A%0A
+%0A
 @app.rou
@@ -2207,19 +2207,17 @@
    title
- = 
+=
 'Databas
@@ -2256,19 +2256,17 @@
     year
- = 
+=
 datetime
@@ -2313,19 +2313,17 @@
 app_name
- = 
+=
 app.conf
@@ -2456,33 +2456,16 @@
     
-g.db.execute(%22
 insert 
-into
+=
  mee
@@ -2473,97 +2473,47 @@
 ings
- (title, time, participants, map_id, creator) VALUES (?, ?, ?, ?, ?)%22,%0A                 %5B
+.insert().values(creator_id='1', title=
 requ
@@ -2527,24 +2527,29 @@
 m%5B'title'%5D, 
+time=
 request.form
@@ -2557,17 +2557,68 @@
 'time'%5D,
- 
+%0A                                      participants=
 request.
@@ -2639,16 +2639,23 @@
 ants'%5D, 
+map_id=
 request.
@@ -2672,17 +2672,8 @@
 id'%5D
-, 'kari'%5D
 )%0A  
@@ -2683,15 +2683,22 @@
 .db.
-commit(
+execute(insert
 )%0A  

change add meeting to sql-alchemy format. Reformat views.py to pep8