"""
Views for the journal component.

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

import httplib
import logging

import flask
import flask_jwt

from rookeries.main import rookeries_app
from rookeries.journal import database as ds


logger = logging.getLogger(__name__)


@rookeries_app.route("/app/pages/<string:page>")
def serve_markdown_page(page=None):
    """
    Serving up a page with Markdown content.

    :request page: The name of the page to display.
    """

    # TODO: Remove hardcoding of landing url
    page = "about" if page == "landing" else page

    journal_entry = None
    data_source = ds.JournalEntryDataStore(flask.current_app.config)
    try:
        journal_entry = data_source[page]
    except KeyError as err:
        logger.warn("Unable to retrieve page: %s", err)
        flask.abort(httplib.NOT_FOUND)

    return flask.jsonify(vars(journal_entry))


@flask_jwt.jwt_required
@rookeries_app.route("/app/pages/<string:page>", methods=['POST', 'PUT'])
def save_markdown_page(page=None):
    # TODO: Remove hardcoding of landing url
    page = "about" if page == "landing" else page

    journal_entry = flask.request.json
    data_source = ds.JournalEntryDataStore(flask.current_app.config)
    existing_document = {}
    try:
        existing_document = vars(data_source[page])
    except KeyError as err:
        logger.warn("Unable to retrieve page: %s", err)

    # TODO Make this more graceful.
    # Reconcile documents.
    for k, v in journal_entry.items():
        existing_document[k] = v

    try:
        data_source[page] = existing_document
    except KeyError as err:
        logger.warn("Unable to save page: %s", err)
        flask.abort(httplib.NOT_ACCEPTABLE)

    return flask.jsonify(vars(data_source[page]))
