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

from django.conf import settings
from django.utils.translation import ugettext as _
from requests.exceptions import HTTPError

from events.common_app.utils import requests_session
from events.yauth_contrib.auth import TvmAuth

logger = logging.getLogger(__name__)


class WebMasterAPIClient:
    def get_hostname(self, host):
        hostname = host['readableHostUrl']
        if hostname.startswith('http://'):
            hostname = hostname[7:]
        return {
            'id': host['hostId'],
            'name': hostname,
        }

    def list_user_hosts(self, uid):
        result = self.get('listUserHosts.json', {'userId': uid, 'showInvisible': 'true'})
        data = result['data']
        if not data:
            return []
        return [
            self.get_hostname(host)
            for host in data['verifiedHosts']
        ]

    def get(self, handle, params=None):
        result = self._make_request(
            handle=handle,
            params=params,
        )
        status = result.get('status')
        if status != 'SUCCESS':
            raise HTTPError(_('WebMaster API return error: {0}').format(
                result.get('errors'))
            )
        return result

    def _make_request(self, handle, params):
        base_url = settings.WEBMASTER_API_URL
        response = requests_session.get(
            url=f'{base_url}/user/host/{handle}',
            params=params,
            timeout=settings.DEFAULT_TIMEOUT,
            verify=settings.YANDEX_ROOT_CERTIFICATE,
            auth=TvmAuth(settings.WEBMASTER_TVM2_CLIENT),
        )
        logger.debug('webmaster response %s %s', response.status_code, response.text)
        response.raise_for_status()
        return response.json()
