"""
Security related functions including user credential authentication and JWT based authentication integration.

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

import collections

import flask
import flask_jwt
from werkzeug import security

Credentials = collections.namedtuple('Credentials', ['username', 'password'])
ADMIN_USERNAME = 'ADMIN_USERNAME'
ADMIN_PASSWORD = 'ADMIN_PASSWORD'

jwt = flask_jwt.JWT()


class User(object):
    def __init__(self, **kwargs):
        self.username = kwargs.get('username')
        self.id = kwargs.get('id')
        self.full_name = kwargs.get('full_name')


@jwt.authentication_handler
def valid_admin_user_credentials(username, password):
    """Checks if the supplied password matches the stored password hash."""
    credentials = Credentials(username, password)
    config = flask.current_app.config
    valid_password = security.check_password_hash(config[ADMIN_PASSWORD], credentials.password)
    if credentials.username == config[ADMIN_USERNAME] and valid_password:
        return User(username=credentials.username, id=1, full_name='Admin')


@jwt.identity_handler
def load_user(payload):
    config = flask.current_app.config
    if payload['user_id'] == 1:
        return User(id=1, username=config[ADMIN_USERNAME], full_name='Admin')


@jwt.auth_response_handler
def jwt_token_response(access_token, identity):
    response = {
        'token': access_token,
        'user': {
            'username': identity.username,
            'fullName': identity.full_name,
        }
    }
    return flask.jsonify(response)
