#!/usr/bin/env python3

from flask import Flask, render_template, url_for, send_from_directory, abort, jsonify
from flask_bootstrap import Bootstrap
from flaskext.markdown import Markdown
from PIL import Image, ImageOps

import os
import random

app = Flask(__name__)
Bootstrap(app)
Markdown(app)

pages = os.path.dirname(os.path.realpath(__file__)) + '/sidor/'

categories = []
photos = []
for x in os.walk(pages):
    if not 'presentation.md' in x[2]:
        continue
    cat = x[0].split('/')[-1]
    categories.append(cat)
    num = len([x for x in x[2] if x.endswith(('.jpg','.JPG'))])
    for i in range(num):
        photos.append({'category': cat, 'num': i})
categories = sorted(categories)

@app.route('/randimg')
def randimg():
    img = random.choice(photos)
    return jsonify(img)

def genimg(imgin, imgout, size):
    img = Image.open(imgin)
    img.thumbnail(size)
    hpad = int((size[0]-img.size[0])/2)
    vpad = int((size[1]-img.size[1])/2)
    thumb = Image.new(mode='RGBA', size=size, color=(255,255,255,0))
    thumb.paste(img, (hpad, vpad))
    thumb.save(imgout)

@app.route('/thumbnails/<category>/')
@app.route('/thumbnails/<category>/<int:num>')
def thumbnails(category, num=0):
    catdir = pages + '/' + category
    thumbdir = catdir + '/thumbnails'
    if not os.path.isfile('%s/%d.jpg' % (thumbdir, num)):
        images = sorted([x for x in next(os.walk(catdir))[2] if x.endswith('.jpg')], key=lambda x: x.lower())
        if not os.path.exists(thumbdir):
            os.makedirs(thumbdir)
        imgin = '%s/%s' % (catdir, images[num])
        imgout = '%s/%d.jpg' % (thumbdir, num)
        genimg(imgin, imgout, (171,180))

    return send_from_directory(thumbdir, filename="%d.jpg" % (num))
@app.route('/slides/<category>/<int:num>')
def slides(category, num=0):
    catdir = pages + '/' + category
    thumbdir = catdir + '/slides'
    if not os.path.isfile('%s/%d.jpg' % (thumbdir, num)):
        images = sorted([x for x in next(os.walk(catdir))[2] if x.endswith('.jpg')], key=lambda x: x.lower())
        imgin = '%s/%s' % (catdir, images[num])
        imgout = '%s/%d.jpg' % (thumbdir, num)
        if not os.path.exists(thumbdir):
            os.makedirs(thumbdir)
        genimg(imgin, imgout, (550,400))

    return send_from_directory(thumbdir, filename="%d.jpg" % (num))

@app.route('/<category>/<int:num>.jpg')
def cat_photo(category, num):
    directory = pages + '/' + category
    images = sorted([x for x in next(os.walk(directory))[2] if x.endswith('.jpg')], key=lambda x: x.lower())
    try:
        return send_from_directory(directory, images[num]);
    except IndexError:
        abort(404)

@app.route('/<category>/')
def category(category):
    directory = pages + '/' + category
    try:
        with open(directory + '/presentation.md') as f:
            presentation = ''.join(f.readlines())
    except FileNotFoundError:
        presentation = ''
    images = len([x for x in next(os.walk(directory))[2] if x.endswith('.jpg')])


    return render_template('category.html', presentation=presentation, categories=categories, category=category, images=images)


@app.route('/')
def index():
    with open(pages + 'startsida.md') as f:
        presentation = ''.join(f.readlines())
    return render_template('index.html', presentation=presentation, categories=categories, img1=random.choice(photos), img2=random.choice(photos))

@app.route('/favicon.ico')
def favicon():
    return send_from_directory('static', filename='favicon.ico')

if __name__ == '__main__':
    app.run(host='0.0.0.0', debug=True)

