# Copyright 2015 Joe H. Rahme <joehakimrahme@gmail.com>
# All Rights Reserved.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.
import argparse
import os

import flask
import mimerender
import six
if six.PY2:
    from exceptions import IOError
    import sys
    reload(sys)  # noqa
    sys.setdefaultencoding('utf-8')

    import builder
    import context
    import utils
else:
    import blogstrap.builder as builder
    import blogstrap.context as context
    import blogstrap.utils as utils


class ArticleNotFound(IOError):
    pass


class ArticleHidden(Exception):
    pass


class ArticleReader(object):

    def __init__(self, path):
        try:
            with open(path) as article_file:
                text = "".join(article_file.readlines())
                text_dict = utils.parse_metadata(text)
                self.content = text_dict['content']
                self.metadata = text_dict['metadata']
        except IOError:
            raise ArticleNotFound(path)

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        pass


class DefaultConfig(object):
    AUTHOR = "Blogstrap"
    DESCRIPTION = "Powered By Blogstrap"
    DEBUG = True
    BLOGROOT = "."
    BLOGTITLE = "Powered by Blogstrap"
    DEFAULT_LANG = "en"
    NAVBAR_LINKS = []
    STATIC_DIR = "images"
    TOC_BLACKLIST = []


# Registering markdown as a valid MIME.
# More info: https://tools.ietf.org/html/rfc7763
mimerender.register_mime('markdown', ('text/markdown',))
mimerender = mimerender.FlaskMimeRender()


def create_app(config_file=None):
    app = flask.Flask(__name__, static_url_path="/framework/static")
    app.config.from_object(DefaultConfig)
    if config_file:
        app.config.from_pyfile(config_file)

    # default static files directory
    staticdir = app.config.get('STATIC_DIR').rstrip("/")
    staticdir_route = os.path.basename(staticdir)

    def _render(template, message=None):
        ctx = context.context(app, message)
        result = flask.render_template(template, **ctx)
        for key, value in ctx.items():
            result = result.replace("{{ %s }}" % key, str(value))
        return result

    def render_html(message):
        return _render("index.html", message)

    def render_html_exception(exception):
        return _render("404.html")

    def render_markdown(message):
        return _render("index.md", message)

    def render_md_exception(exception):
        return _render("404.md")

    @app.route("/")
    def nothing():
        if 'HOMEPAGE' in app.config:
            return serve_blog(blogpost=app.config['HOMEPAGE'])
        # no homepage defined return HTTP 204 No Content
        return ('', 204)

    @app.route("/%s/<image>" % staticdir_route)
    def serve_static(image):
        full_directory = os.path.join(os.getcwd(), staticdir)
        if os.path.exists(os.path.join(full_directory, image)):
            return flask.send_from_directory(full_directory, image)
        else:
            # return 404
            pass

    @app.route("/<blogpost>", strict_slashes=False)