from datacloud.dev_utils.tvm import tvm_id
from datacloud.dev_utils.logging.logger import get_basic_logger

logger = get_basic_logger(__name__)


_URL = 'http://bigb-fast.yandex.ru/bigb?bigb-uid={yuid}&client={client}'
_CLIENT = 'datacloud'


def yuid_to_cid(tvm_manager, yuid, tvm_src=tvm_id.DATACLOUD.prod, timeout=1):
    resp = tvm_manager.tvm_get_request(
        _URL.format(yuid=yuid, client=_CLIENT),
        tvm_src, tvm_id.BIGB.prod, timeout=timeout)
    if not resp:
        logger.warn('Broken response from tvm_manager')
        return None
    if resp.status_code != 200:
        logger.warn('Failed BigB request: {}'.format(resp.status_code))
        return None
    try:
        data = resp.json() \
            .get('data', [{}])[0].get('segment', [{}])[0].get('data', {})
        return data.get('CryptaId', None)
    except (ValueError, IndexError) as ex:
        logger.warn('Can not decode BigB response {}'.format(ex))
    return None
