# -*- coding: utf-8 -*-


from django.conf import settings

from tvm2 import TVM2
from django_yauth.authentication_mechanisms.cookie import Mechanism

DATA_FROM_REQUEST_EXTRACTOR = Mechanism()


class TVM2Error(Exception):
    pass


def get_params_for_user_ticket(request):
    from events.yauth_contrib.mechanisms.http_header import get_authorization_token
    extractor = DATA_FROM_REQUEST_EXTRACTOR
    session_id = get_authorization_token('sessionid', request)
    if not session_id:
        session_id = request.COOKIES.get('Session_id')
    host = extractor.get_current_host(request)
    user_ip = extractor.get_user_ip(request)
    return session_id, host, user_ip


def get_tvm2_client():
    client = init_tvm2_client()
    if client.blackbox_client.name != settings.BLACKBOX_CLIENT.name:
        TVM2._instance = None
        client = init_tvm2_client()
    return client


def init_tvm2_client():
    return TVM2(
        client_id=settings.TVM2_CLIENT_ID,
        secret=settings.TVM2_SECRET,
        blackbox_client=settings.BLACKBOX_CLIENT,
        destinations=settings.TVM2_DESTINATIONS,
        allowed_clients=settings.YAUTH_TVM2_ALLOWED_CLIENT_IDS,
    )


def get_user_ticket(request):
    ticket_in_request = request.META.get(settings.YAUTH_TVM2_USER_HEADER)
    if ticket_in_request:
        return ticket_in_request
    tvm2_client = get_tvm2_client()
    session_id, server_host, user_ip = get_params_for_user_ticket(request)
    if not session_id:
        raise TVM2Error('Dont get session id from request')
    user_ticket = tvm2_client.get_user_ticket(
        session_id=session_id,
        user_ip=user_ip,
        server_host=server_host,
    )
    if not user_ticket:
        raise TVM2Error('Dont get user ticket from blackbox')
    return user_ticket


def get_service_ticket(client_id):
    if settings.IS_TEST:
        return '123'
    tvm2_client = get_tvm2_client()
    service_tickets = tvm2_client.get_service_tickets(client_id)
    service_ticket = service_tickets.get(client_id)
    if not service_ticket:
        raise TVM2Error('Dont get service ticket for {}'.format(client_id))
    return service_ticket
