import logging
import requests

from django.conf import settings


logger = logging.getLogger(__name__)


class AmazingHiringError(Exception):

    def __init__(self, message='amazing_hiring_error'):
        self.message = message


class AmazingHiringNotFoundError(AmazingHiringError):

    def __init__(self, message='amazing_hiring_not_found_error'):
        self.message = message


class AmazingHiringAPI:

    @classmethod
    def _get(cls, path):
        url = settings.AMAZING_HIRING_API_URL + path
        try:
            response = requests.get(
                url=url,
                params={
                    'format': 'json',
                },
                headers={
                    'Authorization': f'Token {settings.AMAZING_HIRING_TOKEN}',
                },
                timeout=10,
            )
            logger.info('Amazing Hiring response: %s', response.content.decode('utf-8'))
        except (requests.ConnectionError, requests.Timeout):
            logger.exception('Amazing Hiring is not responding')
            raise AmazingHiringError('amazing_hiring_no_response')

        if response.status_code == 404:
            raise AmazingHiringNotFoundError

        try:
            data = response.json()
        except ValueError:
            logger.exception('Error during parse Amazing Hiring response')
            raise AmazingHiringError('amazing_hiring_invalid_response')

        return data

    @classmethod
    def get_profile(cls, profile_id):
        return cls._get(f'profiles/{profile_id}/')
