"""
Creates and configures the Rookeries Flask app

:copyright: Copyright 2013-2015, Dorian Pula <dorian.pula@amber-penguin-software.ca>
:license: AGPL v3+
"""

import httplib

import flask
from werkzeug import exceptions

from rookeries import security


def make_json_app(import_name, **kwargs):
    """Creates a JSON-oriented Flask app.

    All error responses that you don't specifically manage yourself will have a application/json content type, and
    will contain JSON in following format: ::

        { "error": {
                "code": 405,
                "message": "Method Not Allowed"
            }
        }

    Originally Pavel Repin's `snippet receipe for JSON response apps <http://flask.pocoo.org/snippets/83/>`_.


    :param import_name: The name of the app to import.
    """

    def make_json_error(error):
        """
        Make a JSON error response.

        :param error: The error message to turn into JSON.
        """
        error_message = error.name if isinstance(error, exceptions.HTTPException) else str(error)
        error_code = error.code if isinstance(error, exceptions.HTTPException) else httplib.INTERNAL_SERVER_ERROR
        error_json = {"error": {"code": error_code, "message": error_message}}

        response = flask.jsonify(error_json)
        response.status_code = error_code
        return response

    web_app = flask.Flask(import_name, **kwargs)

    for code in iter(exceptions.default_exceptions):
        web_app.error_handler_spec[None][code] = make_json_error

    security.jwt.init_app(web_app)
    return web_app
