# -*- coding: utf-8 -*-
import httpx

from tvm2.protocol import BLACKBOX_MAP
from tvmauth import BlackboxTvmId

from .conf import AppTypeSettings
from .http import HttpxTvmAuth


class BaseBlackbox:
    timeout = (1, 5)
    name = None
    host = None

    def __init__(self, settings: AppTypeSettings, name: str = None):
        self.settings = settings
        self.blackbox_client = BlackboxTvmId[name or self.name]
        self.url = BLACKBOX_MAP[self.blackbox_client]['url']
        self.auth = HttpxTvmAuth(settings, self.blackbox_client.value, self.blackbox_client.name)

    async def _make_request(self, method, **params):
        params.update({
            'method': method,
            'format': 'json',
            'host': self.host,
        })
        async with httpx.AsyncClient() as client:
            response = await client.get(self.url, params=params, auth=self.auth, timeout=self.timeout)
            if response.status_code == 200:
                result = response.json()
                if result.get('error') == 'OK' and result.get('status', {}).get('value') == 'VALID':
                    return result

    async def sessionid(self, session_id: str, user_ip: str):
        params = {
            'sessionid': session_id,
            'userip': user_ip,
        }
        result = await self._make_request('sessionid', **params)
        if result:
            return result.get('uid', {}).get('value')


class InternalBlackbox(BaseBlackbox):
    name = 'ProdYateam'
    host = 'forms.yandex-team.ru'


class ExternalBlackbox(BaseBlackbox):
    name = 'Prod'
    host = 'forms.yandex.ru'
