#!/usr/bin/env python
import sys

from flask import Flask, render_template, request
from flask_flatpages import FlatPages
import arrow

DEBUG = True
FLATPAGES_AUTO_RELOAD = DEBUG
FLATPAGES_EXTENSION = '.md'
FLATPAGES_ROOT = 'pages'
FLATPAGES_MARKDOWN_EXTENSIONS = ['codehilite', 'extra']

app = Flask(__name__)
app.config.from_object(__name__)
pages = FlatPages(app)

permalinks = {}
blogposts = []
tags = set()
# Find all pages
for page in pages:
    if page.meta.get('permalink', None):
        # Special page
        page.meta['url'] = page.meta['permalink']
    else:
        # Blog post
        blogposts.append(page)
        tags.update(page.meta.get('tags', []))
        # Setup permalink
        parts = page.path.split('-')
        page.meta['url'] = '/blog/{}/{}/{}/'.format(parts[0], parts[1], '-'.join(parts[3:]))

        # Find and format post publication date
        date = arrow.get('-'.join(parts[0:3]))
        page.meta['date'] = date
        page.meta['datestr'] = date.format('D MMM YYYY')

    permalinks[page.meta['url']] = page
blogposts = sorted(blogposts, key=lambda p: p.meta['date'], reverse=True)



# Permalinks
@app.route("/")
@app.route("/<path:path>")
def page(path=''):
    page = permalinks['/'+path]
    template = 'blog_post.html' if page in blogposts else 'page.html'
    return render_template(template, page=page)

# Blog listings
@app.route("/blog/")
@app.route("/blog/<string:tag>/")
def blog_listing(tag=None):
    posts = blogposts
    if tag:
        posts = [post for post in posts if tag in post.meta.get('tags', [])]
    return render_template('blog_listing.html', posts=posts, tags=tags, title=tag)


if __name__ == "__main__":
    if len(sys.argv) > 1 and sys.argv[1] == "build":
        from flask_frozen import Freezer
        from glob import iglob
        from shutil import move, rmtree
        import os
        freezer = Freezer(app)

        # Make sure we get all pages
        @freezer.register_generator
        def page():
            for link in permalinks:
                yield {'path': link}
        @freezer.register_generator
        def blog_listing():
            yield {'tag': None}
            for tag in tags:
                yield {'tag': tag}

        # Freeze site
        freezer.freeze()

        # Move static files
        root = os.path.dirname(os.path.realpath(__file__))
        for f in iglob(os.path.join(root, 'build/static/*')):
            end = f[len(os.path.join(root, 'build/static/')):]
            move(f, os.path.join(root, 'build/'+end))
        rmtree(os.path.join(root, 'build/static/'))

    else:
        # Serve static files too
        @app.route("/media/<path:path>")
        @app.route("/src/<path:path>")
        @app.route("/favicon.ico")
        def static_file(path=None):
            return app.send_static_file(request.path[1:])

        app.run()
