"""
Views for managing sites.

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

import http
import logging

import flask
import jsonschema

from rookeries import database
from rookeries.main import rookeries_app
from rookeries.sites import models, schema
from rookeries.vendors import flask_jwt

logger = logging.getLogger(__name__)


@rookeries_app.route('/api/site', methods=['PUT'])
@flask_jwt.jwt_required()
def update_site():
    # Check if request is JSON, and respects the JSON schema
    if not flask.request.is_json:
        flask.abort(http.HTTPStatus.BAD_REQUEST)

    incoming_request = flask.request.get_json()
    jsonschema.validate(
        incoming_request, schema.SITE_CREATION_MODIFICATION_SCHEMA)

    # Modifies a site from the JSON.
    try:
        db = database.CouchDB.configure_from_env()
        # TODO: Make this query use nicer defaults.
        existing_site = models.Site.find_in_db(db, {})

        # TODO: Figure out nice way to update from the incoming request...
        desired_site = models.Site(**incoming_request)
        existing_site.name = desired_site.name
        existing_site.menu = desired_site.menu
        existing_site.config = desired_site.config
        # TODO: Put to site... gah... this is icky.

        # TODO: Extract request to become part of model.
        logger.info('Updating site...')
        db.create_or_update_document(
            existing_site.to_db_json(),
            existing_site._id,
            existing_site._rev
        )

        updated_site = models.Site.find_in_db(db, {})

        return flask.jsonify(updated_site.to_api_json()), http.HTTPStatus.OK
    except database.NoMatchingDocumentFoundError:
        # TODO: Add tests for this unlikely scenario.
        logger.error('No site found!  Create one first')
        flask.abort(http.HTTPStatus.INTERNAL_SERVER_ERROR)


@rookeries_app.route('/api/site', methods=['GET'])
def get_site():
    try:
        db = database.CouchDB.configure_from_env()
        site = models.Site.find_in_db(db, {})
        return flask.jsonify(site.to_api_json())
    except database.NoMatchingDocumentFoundError:
        # TODO: Add tests for this unlikely scenario.
        logger.error('No site found!  Create one first')
        flask.abort(http.HTTPStatus.INTERNAL_SERVER_ERROR)
