"""
Views for managing sites.

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

import http
import logging

import flask

from rookeries import database
from rookeries.sites import models

from rookeries.main import rookeries_app


logger = logging.getLogger(__name__)
ROOKERIES_API_KEY_HEADER = 'ROOKERIES_API_KEY'

# TODO: Add in functionality to create and updates sites and menus.


@rookeries_app.route('/api/site', methods=['GET'])
def app_config():

    # Get API Key from header
    api_key = flask.request.headers.get(ROOKERIES_API_KEY_HEADER)
    if not api_key:
        logger.error('No ROOKERIES_API_KEY header found in request!')
        flask.abort(http.HTTPStatus.BAD_REQUEST)

    site = None
    db_session = database.SQLAlchemy.session
    try:
        site = db_session.query(models.Site).filter_by(api_key=api_key).first()
    except Exception as err:
        logger.error(f'Error retrieving site because of: {err}')
        flask.abort(http.HTTPStatus.INTERNAL_SERVER_ERROR)

    if site is None:
        logger.warn('Unable to find retrieve app')
        flask.abort(http.HTTPStatus.NOT_FOUND)

    return flask.jsonify(site.to_json())


@rookeries_app.route('/api/site/menu', methods=['GET'])
def menu_config():

    # Get API Key from header
    api_key = flask.request.headers.get(ROOKERIES_API_KEY_HEADER)
    if not api_key:
        logger.error('No ROOKERIES_API_KEY header found in request!')
        flask.abort(http.HTTPStatus.BAD_REQUEST)

    site = None
    db_session = database.SQLAlchemy.session
    try:
        site = db_session.query(models.Site).filter_by(api_key=api_key).first()
    except Exception as err:
        logger.error(f'Error retrieving site because of: {err}')
        flask.abort(http.HTTPStatus.INTERNAL_SERVER_ERROR)

    if site is None:
        logger.warn('Unable to find retrieve app')
        flask.abort(http.HTTPStatus.NOT_FOUND)

    nav_menu = {'menu': [menu_item.to_json() for menu_item in site.menu]}
    return flask.jsonify(nav_menu)
