"""
Views for managing users.

: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 rookeries import database
from rookeries.main import rookeries_app
from rookeries.sites import views
from rookeries.users import models

logger = logging.getLogger(__name__)


@flask_jwt.jwt_required
@rookeries_app.route('/api/users/<user_id>', methods=['GET'])
def get_user(user_id):

    # Get API Key from header
    api_key = flask.request.headers.get(views.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:
        # TODO: Figure out user access model to Apps and Views, relationship etc.
        site = db_session.query(models.User).filter_by(api_key=api_key, id=user_id).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())


@flask_jwt.jwt_required
@rookeries_app.route('/api/users', methods=['POST'])
def create_user():

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

    # TODO: Check against roles of user.

    site = None
    db_session = database.SQLAlchemy.session
    try:
        # TODO: Creates a user here... some how?
        user = models.User(**flask.request.json)
        user.api_key = api_key
        site = db_session.add(user)
    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())


@flask_jwt.jwt_required
@rookeries_app.route('/api/users/<user_id>', methods=['PUT'])
def update_user(user_id):
    flask.abort(http.HTTPStatus.NOT_IMPLEMENTED)
