"""
Views for managing pages.

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

import http
import logging

import flask
import flask_jwt
from sqlalchemy.orm import exc as sql_error

from rookeries import database
from rookeries.pages import models

from rookeries.main import rookeries_app

logger = logging.getLogger(__name__)


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

    :request page: The name of the page to display.
    """
    # TODO: Remove hardcoding of landing url
    return serve_page('about')


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

    page = None
    db_session = database.SQLAlchemy.session
    try:
        # TODO: Filter by provided APP ID, provided in the header.
        page = db_session.query(models.Page).filter_by(slug=slug).first()
    except Exception as err:
        logger.error(f'Error retrieving "{slug}" page because of: {err}')
        flask.abort(http.HTTPStatus.INTERNAL_SERVER_ERROR)

    if page is None:
        logger.warn('Unable to find retrieve page: %s', slug)
        flask.abort(http.HTTPStatus.NOT_FOUND)

    return flask.jsonify(page.to_json())


@flask_jwt.jwt_required
@rookeries_app.route('/api/pages/<slug>', methods=['POST', 'PUT'])
def save_page(slug):
    updated_page = flask.request.json
    db_session = database.SQLAlchemy.session
    page = None
    try:
        # TODO: Filter by provided APP ID, provided in the header.
        page = db_session.query(models.Page).filter_by(slug=slug).first()
    except sql_error.NoResultFound:
        page = models.Page(
            slug=slug,
            title=updated_page['title'],
            content=updated_page['content'])
        db_session.add(page)
    except Exception as err:
        logger.error(f'Error retrieving "{slug}" page because of: {err}')
        flask.abort(http.HTTPStatus.INTERNAL_SERVER_ERROR)
    else:
        page.slug = slug
        page.title = updated_page['title']
        page.content = updated_page['content']

    return flask.jsonify(page.to_json())
