# coding: utf-8


from django.conf import settings
from tvm2 import TVM2
from tvm2.exceptions import NotAllTicketsException

is_initialized = False


def get_tvm_client():
    global is_initialized
    if not is_initialized:
        destinations = set()
        is_initialized = True
    else:
        destinations = []

    allowed_clients = '*'
    blackbox_client = settings.INTERNAL_BLACKBOX_CLIENT

    return TVM2(
        client_id=settings.TVM2_CLIENT_ID,
        secret=settings.TVM2_SECRET,
        blackbox_client=blackbox_client,
        destinations=destinations,
        allowed_clients=allowed_clients,
    )


def get_tvm_ticket(destination):
    tvm_client = get_tvm_client()
    if destination not in tvm_client.destinations:
        tvm_client.add_destinations(destination)
    tickets = tvm_client.get_service_tickets(destination)
    if destination in tickets and tickets[destination]:
        return tickets[destination]
    else:
        raise NotAllTicketsException()
