from ticket_parser2.api.v1 import TvmClient, TvmApiClientSettings, BlackboxEnv

import settings
import logging


class Ticketer:
    def __init__(self):
        self._client = TvmClient(TvmApiClientSettings(
            self_client_id=settings.TVM_CLIENT_ID,
            enable_service_ticket_checking=True,
            enable_user_ticket_checking=BlackboxEnv.Prod,
            self_secret=settings.TVM_CLIENT_SECRET,
            dsts={'overload': settings.TVM_CLIENT_ID, 'takeout': settings.TAKEOUT_ID, 'blackbox': settings.BLACKBOX_ID, 'gozora': settings.GOZORA_ID},
        ))
        self._allowed_consumers = [settings.TVM_CLIENT_ID, settings.TAKEOUT_ID, settings.PASSPORT_PROFILE_PROD, settings.PASSPORT_PROFILE_TEST, settings.BLACKBOX_ID, settings.GOZORA_ID]

    def get_ticket(self, service):
        return self._client.get_service_ticket_for(service)

    def check_ticket(self, ticket):
        try:
            service_tickets = self._client.check_service_ticket(ticket)
            if service_tickets.src not in self._allowed_consumers:
                logging.error('Access denied for service %s', service_tickets.src)
                return False
        except Exception:
            logging.error('No service ticket received', exc_info=True)
            return False

        return True

    def stop(self):
        self._client.stop()


if __name__ == '__main__':
    ticketer = Ticketer()
    ticket_overload = ticketer.get_ticket('overload')
    ticket_takeout = ticketer.get_ticket('takeout')
    ticket_blackbox = ticketer.get_ticket('blackbox')
    assert ticketer.check_ticket(ticket_takeout) & ticketer.check_ticket(ticket_blackbox)
