from functools import wraps

from blackbox import JsonBlackbox
from flask import redirect, request, g, current_app
from tvm2.protocol import BlackboxClientId


def passport_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if current_app.config['PASSPORT_OFF']:
            return f(*args, **kwargs)
        if 'HTTP_X_FORWARDED_FOR' in request.environ:
            address = request.environ.get('HTTP_X_FORWARDED_FOR')
        else:
            address = request.environ.get('REMOTE_ADDR')
        current_app.logger.info(request.cookies)
        session_cook = request.cookies.get('Session_id')
        if request.is_secure:
            ssl_session_cook = request.cookies.get('sessionid2')
        if not session_cook:
            current_app.logger.info('Session_ID not found, redirecting for auth in passport')
            return redirect(current_app.config['PASSPORT_LOGIN_URL'])
        bb = JsonBlackbox('http://blackbox.yandex-team.ru/blackbox/', tvm2_client_id=current_app.config['PASSPORT_TVM_ID'],
                          tvm2_secret=current_app.config['PASSPORT_TVM_SECRET'], blackbox_client=BlackboxClientId.ProdYateam)
        result = bb.sessionid(address, session_cook, current_app.config['BASE_HOST'],
                              sslsessionid=ssl_session_cook if request.is_secure else None)
        current_app.logger.info(result)
        if result['status']['value'] == 'VALID':
            g.passport = result
        return f(*args, **kwargs)

    return decorated_function
