"""
Views for managing pages.

:copyright: Copyright 2013-2017, Dorian Puła
    <dorian.pula@amber-penguin-software.ca>
:license: AGPL v3+
"""

import http
import logging

import flask

from rookeries import database
from rookeries.main import rookeries_app
from rookeries.pages import models
from rookeries.sites import models as site_models
from rookeries.vendors import flask_jwt

logger = logging.getLogger(__name__)


@rookeries_app.route('/api/pages/', methods=['GET'])
@rookeries_app.route('/api/pages/<slug>', methods=['GET'])
def serve_page(slug=''):
    """
    Serving up a page with Markdown content.

    :request page: The name of the page to display.
    """
    logger.info('Retrieving page "%s"', slug)

    # TODO: Attach DB to Flask app context.
    db = database.CouchDB.configure_from_env()
    try:

        # TODO: Get rid of this once frontend improved to not call 'root slug'
        if not slug:
            # TODO: Remove the need for such a default value.
            site = site_models.Site.find_in_db(db, {})
            slug = site.landing_page

        page = models.Page.find_in_db(db, {'slug': slug})
        return flask.jsonify(page.to_api_json())
    except database.NoMatchingDocumentFoundError:
        flask.abort(http.HTTPStatus.NOT_FOUND)


@rookeries_app.route('/api/pages/<slug>', methods=['POST', 'PUT'])
@flask_jwt.jwt_required()
def save_page(slug):
    # TODO: Remove SQL database parts
    updated_page = flask.request.json
    page = models.Page.query.filter((models.Page.slug == slug)).first_or_404()
    if not page:
        page = models.Page(
            slug=slug,
            title=updated_page['title'],
            content=updated_page['content'])
        # db.session.add(page)

    else:
        page.slug = slug
        page.title = updated_page['title']
        page.content = updated_page['content']

    # db.session.commit()
    return flask.jsonify(page.to_json())
