import logging
import requests
import waffle

from requests.exceptions import ConnectionError, Timeout

from django.conf import settings

logger = logging.getLogger(__name__)


class TableFlowAPI:

    @classmethod
    def _request(cls, method, url, params=None, data=None):
        headers = {
            'Authorization': 'OAuth %s' % settings.FEMIDA_ROBOT_TOKEN,
        }

        try:
            response = requests.request(
                method=method,
                url=settings.TABLE_FLOW_URL + url,
                params=params,
                json=data,
                timeout=10,
                headers=headers,
            )
        except (ConnectionError, Timeout):
            logger.exception('Table-flow is not responding')
            return None

        if not response.ok:
            logger.warning(
                'Table-flow error %s, response: %s',
                response.status_code,
                response.content.decode('utf-8'),
            )
            return None

        try:
            return response.json() if response.content else {}
        except ValueError:
            logger.exception(
                'Error during parse Table-flow response: %s',
                response.content.decode('utf-8'),
            )
            return None

    @classmethod
    def _get(cls, url, params=None):
        return cls._request('GET', url, params=params)

    @classmethod
    def get_hire_order_offer_params(cls, department):
        if not waffle.switch_is_active('enable_table_flow'):
            return {}
        url = '/rules/femida_hire_orders/execute/'
        return cls._get(url, params={'dep': department})
