# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from datacloud.score_api.server.errors import ApiException


def get_address(request):
    """ Extracts client IP from Flask request """
    if 'HTTP_X_FORWARDED_FOR_Y' in request.environ:
        address = request.environ.get('HTTP_X_FORWARDED_FOR_Y')
    elif 'HTTP_X_FORWARDED_FOR' in request.environ:
        address = request.environ.get('HTTP_X_FORWARDED_FOR')
    else:
        address = request.environ.get('REMOTE_ADDR')
    return address


class UserLoader(object):
    def __init__(self, user_storage):
        super(UserLoader, self).__init__()
        self._user_storage = user_storage

    def __call__(self, request):
        address = get_address(request)
        auth_header = request.headers.get('Authorization', None)

        if auth_header:
            # YDB can not work with unicode
            auth_header = auth_header.encode('utf-8')

        user = self._user_storage.get_user_by_token(auth_header, address=address)
        if not user:
            # WTF? Why return user here if no user?? (by re9ulusv)
            return user  # invalid user
        return user


class Unauthorized(ApiException):
    """ Anonymous user """
    status_code = 401
    code = 'unauthorized'


def unauthorized_handler():
    raise Unauthorized()
