"""Hacks needed to circumvent connexion validation

There is a bug on the connexion library concerning content negotiation and
response validation. See https://github.com/zalando/connexion/issues/860 and
https://github.com/zalando/connexion/pull/760

Until this issue is fixed, we need to find a way to avoid a false validation
error when a requests sends an 'application/geo+json' accept header
"""
import functools
import logging

from connexion.decorators.response import ResponseValidator
from connexion import problem
from connexion.exceptions import NonConformingResponseBody, NonConformingResponseHeaders
from connexion.utils import has_coroutine

logger = logging.getLogger(__name__)


class ValidatorWorkaround(ResponseValidator):
    def validate_response_with_request(
        self, request, data, status_code, headers, url
    ):
        if request.headers.get('accept', '') == 'application/geo+json':
            logging.debug('Circumventing validation for application/geo+json')
            return True
        return self.validate_response(data, status_code, headers, url)

    def __call__(self, function):
        """
		:type function: types.FunctionType
		:rtype: types.FunctionType
		"""
        def _wrapper(request, response):
            connexion_response = \
             self.operation.api.get_connexion_response(response, self.mimetype)
            self.validate_response_with_request(
                request, connexion_response.body,
                connexion_response.status_code, connexion_response.headers,
                request.url
            )

            return response

        if has_coroutine(function):
            from .coroutine_wrappers import get_response_validator_wrapper
            wrapper = get_response_validator_wrapper(function, _wrapper)

        else:  # pragma: 3 no cover

            @functools.wraps(function)
            def wrapper(request):
                response = function(request)
                return _wrapper(request, response)

        return wrapper
