"""
Views for managing pages.

:copyright: Copyright 2013-2017, Dorian Pula <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.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()
    found_page = db.find_first_document({
            'type': models.Page.doc_type(),
            'slug': slug,
        })

    if not found_page:
        flask.abort(http.HTTPStatus.NOT_FOUND)

    page = models.Page(**found_page)
    return flask.jsonify(page.to_api_json())


@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())
