"""
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.main import rookeries_app
from rookeries.sites import models, schema
from rookeries.users import models as user_models
from rookeries.vendors import flask_jwt

logger = logging.getLogger(__name__)

# TODO: Add in functionality to create and update sites.
# TODO: Add in ability to query on collections of sites.


def add_self_link(site_json):
    # TODO: Consider creating a better way to resolve IDs in links to
    # TODO: resources, in a generic manner.
    site_json['urls'] = {
        'self': flask.url_for('rookeries_app.get_site', _external=True),
    }
    return site_json


# TODO: Rework to only allow patching of parts of the site.
@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)

    # Check if user allowed to modify a site.
    current_user = flask_jwt.current_identity
    requesting_user_role = user_models.UserRole[current_user['role']]

    if requesting_user_role != user_models.UserRole.admin:
        flask.abort(http.HTTPStatus.UNAUTHORIZED)

    # Modifies a site from the JSON.
    existing_site = models.Site.query\
        .filter_by(name=models.MAIN_SITE_ROOT_BLOCK).first_or_404()
    updated_site = models.Site.from_json(incoming_request)
    existing_site.base_url = updated_site.base_url
    # TODO: db.session.commit()

    site_response = add_self_link(existing_site.to_json())
    return flask.jsonify(site_response), http.HTTPStatus.OK


@rookeries_app.route('/api/site', methods=['GET'])
def get_site():
    # site = models.Site.query.filter_by(name=models.MAIN_SITE_ROOT_BLOCK)\
    #     .first_or_404()
    # site_response = add_self_link(site.to_json())

    # TODO: Use mock site until we figure out setup.
    site_response = {
        'name': 'Rookeries',
        'landingPage': 'about',
        'urls': {'self': '/api/site'},
        'config': {
            'footer': 'Rookeries - © 2013-2017 - Amber Penguin Software',
            'favicon': '/static/images/mr-penguin-amber-favicon.ico',
            'name': 'Rookeries',
            'tagline': 'Simple Site Construction',
            'logo': '/static/images/mr-penguin-amber.svg',
        },
        'menu': []
    }

    return flask.jsonify(site_response)
