#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
from flask import request, session, g, redirect, url_for, abort, render_template, flash
from zlasker import app, db


@app.route('/')
def show_entries():
    return render_template('show_entries.html', entries=db.get_entries())


@app.route('/add', methods=['POST'])
def add_entry():
    if not session.get('logged_in'):
        abort(401)
    db.add_entry(request.form['title'], request.form['text'])
    flash('New entry successfully posted')
    return redirect(url_for('show_entries'))


@app.route('/login', methods=['GET', 'POST'])
def login():
    error = None
    if request.method == 'POST':
        if request.form['username'] != app.config['USERNAME']:
            error = 'Invalid username'
        elif request.form['password'] != app.config['PASSWORD']:
            error = 'Invalid password'
        else:
            session['logged_in'] = True
            flash('You are logged in')
            return redirect(url_for('show_entries'))
    return render_template('login.html', error=error)


@app.route('/logout')
def logout():
    session.pop('logged_in', None)
    flash('You are logged out')
    return redirect(url_for('show_entries'))
