from vault_client.instances import Production as VaultClient
from settings import BLACKBOX_URL, TVM_ID, YAUTH_TVM2_SECRET, BLACKBOX_TVM_ID, YAV_OAUTH_TOKEN
from tvm2 import TVM2
from ticket_parser2_py3.api.v1 import BlackboxClientId
import requests
import logging


def _get_uid_(login):
    url = '{blackbox}/?method=userinfo&login={login}&sid=passport&userip=127.0.0.1&format=json'.format(blackbox=BLACKBOX_URL, login=login)
    headers = {'X-Ya-Service-Ticket': get_blackbox_service_ticket()}
    try:
        response = requests.get(url, headers=headers).json()
        if response and 'users' in response:
            uid = response.get('users')[0].get('id')
            logging.info('The user %s has a uid %s', login, uid)
            return uid
    except Exception:
        logging.error('Failed request to the blackbox for user %s.', login, exc_info=True)


def get_token(secret, key, user):
    try:
        client = VaultClient(
            authorization='OAuth {}'.format(YAV_OAUTH_TOKEN),
            decode_files=True
        )
        logging.info('Check the token %s permissions for user %s and user robot-lunapark', key, user)
        if (client.can_user_read_secret(secret_uuid=secret, uid=_get_uid_(user), return_raw=True).json()['access'] == 'allowed' 
            and client.can_user_read_secret(secret_uuid=secret, uid=_get_uid_('robot-lunapark'), return_raw=True).json()['access'] == 'allowed'):
            logging.info('We can to use the secret %s.', secret)
            tokens = client.get_version(secret)
            if tokens and key in tokens.get('value', {}):
                return tokens.get('value').get(key)
            else:
                logging.error('The secret %s doesn\'t contain the key %s', secret, key)
        else:
            logging.error('No read permission to secret %s for user robot-lunapark or user %s ', secret, user)
    except Exception:
        logging.error('Failed to get secret from the Vault.', exc_info=True)


def get_blackbox_service_ticket():
    try:
        return TVM2(
            client_id=TVM_ID,
            secret=YAUTH_TVM2_SECRET,
            allowed_clients=('*',),
            blackbox_client=BlackboxClientId.ProdYateam,
            destinations={str(BLACKBOX_TVM_ID): BLACKBOX_TVM_ID}
        ).get_service_tickets(str(BLACKBOX_TVM_ID))[str(BLACKBOX_TVM_ID)]
    except Exception:
        logging.error('Can\'t receive service ticket for blackbox', exc_info=True)
