from flask import Flask, render_template, request, redirect, url_for
from flask_sqlalchemy import SQLAlchemy
from flask.ext.uploads import UploadSet, configure_uploads, IMAGES
from werkzeug.utils import secure_filename
from datetime import datetime
from random import choice
from functools import wraps
import os

app = Flask(__name__)

UPLOAD_FOLDER = 'static/'
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'

db = SQLAlchemy(app)

class Blogpost(db.Model):
    userid = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(50))
    author = db.Column(db.String(20))
    date_posted = db.Column(db.DateTime)
    content = db.Column(db.Text)
    image = db.Column(db.Text)


class User:
    def __init__(self, username, password):
        self.session = {}
        self.username = username
        self.password = password

dean = User('dean', 'bloggy')

@app.route('/')
def index():
    bgs = [ 'blog-bg1.jpg',
            'blog-bg2.jpg',
            'blog-bg3.jpg',
            'blog-bg4.jpg',
            'blog-bg5.jpg',]
    bg = choice(bgs)
    posts = Blogpost.query.order_by(Blogpost.date_posted.desc()).all()
    return render_template('index.html', posts=posts, filename=bg)

def login_required(test):
    @wraps(test)
    def wrap(*args, **kwargs):
        if 'logged_in' in dean.session:
            return test(*args, **kwargs)
        else:
            return redirect(url_for('login'))
    return wrap

@app.route("/signin", methods = ['GET', 'POST'])
def login():
    error = None
    if request.method == 'POST':
        if request.form['username'] == dean.username or request.form['password'] == dean.password:
            dean.session['logged_in'] = True
            return redirect(url_for('add'))
        else:
            error = "Wrong username or password"
    return render_template("login.html", error=error)

@app.route('/add')
@login_required
def add():
    bgs = ['add-bg1.jpg','add-bg2.jpg','add-bg3.jpg']
    bg = choice(bgs)
    return render_template('add.html',filename=bg)

@app.route('/post/<int:post_id>')
def post(post_id):
    post = Blogpost.query.filter_by(userid=post_id).one()
    print('{} \n{} \n{} \n        {}\n'.format(post.author, post.title, post.content, post.image))
    if post.image:
        filename= post.image
    else:
        filename='home-bg.jpg'
    return render_template('post.html', post=post, filename=filename)

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS


@app.route('/addpost', methods=['POST'])
def addpost():
    title = request.form['title']
    author = request.form['author']
    content = request.form['content']
    if request.method == 'POST':
        image = request.files['image']
        img_filename = secure_filename(image.filename)
        image.save(os.path.join(app.config['UPLOAD_FOLDER'], img_filename))
    else:
        img_filename=None
    post = Blogpost(title=title, author=author, date_posted=datetime.now(),  content=content, image=img_filename) 
    db.session.add(post)
    db.session.commit()
    return redirect(url_for('index'))

@app.route('/addimage', methods=['POST'])
def addimage():
    if request.method == 'POST' and 'image' in request.files:
        image = request.files['image']
        if image and allowed_file(image.filename):
            img_filename = secure_filename(image.filename)
            image.save(os.path.join(app.config['UPLOAD_FOLDER'], img_filename))
    else:
        img_filename=None
    return None

@app.route('/about')
def about():
    bg = 'about-bg.jpg'
    return render_template('about.html', filename=bg)

if __name__ == '__main__':
    db.create_all()
    app.run(debug=True)
