# Path: src/publisher/utils.py
# def isint(v):
#     try:
#         int(v)
#         return True
#     except (ValueError, TypeError):
#         return False
# 
# Path: src/publisher/api_v2_views.py
# def flatten_accept(accepts_header_str):
#     "returns a list of triples like [(mime, 'version', version), ...]"
#     lst = []
#     if not accepts_header_str:
#         return lst
#     for mime in accepts_header_str.split(","):
#         # ('application/vnd.elife.article-vor+json', {'version': 2})
#         parsed_mime, parsed_params = parse_header(mime.encode())
#         # ('*/*', 'version', None)
#         # ('application/json', 'version', None)
#         # ('application/vnd.elife.article-poa+json', 'version', 2)
#         version = parsed_params.pop("version", b"").decode("utf-8")
#         lst.append((parsed_mime, "version", version or None))
#     return lst
# 
# def _ctype(content_type_key):
#     "returns a content type for the given `content_type_key`."
#     assert content_type_key in settings.CONTENT_TYPES
#     return "application/vnd.elife.article-%s+json" % content_type_key
# 
# def http_406():
#     "returns a HTTP 406 json error response (couldn't negotiate content type with request)."
#     title = "not acceptable"
#     detail = "could not negotiate an acceptable response type"
#     return error_response(406, title, detail)


from django.conf import settings
from .utils import isint
from .api_v2_views import flatten_accept, _ctype, http_406
import json
import logging
# todo: this middleware needs to go away and `error_response` in api_v2_views needs to
# emit responses valid against https://datatracker.ietf.org/doc/html/rfc7807 and
# https://github.com/elifesciences/api-raml/blob/develop/dist/model/error.v1.json
def error_content_check(get_response_fn):
    """This middleware ensures all unsuccessful responses have the correct structure."""

    def middleware(request):
        response = get_response_fn(request)
        if response.status_code > 399 and "json" in get_content_type(response):
            body = json.loads(response.content.decode("utf-8"))
            if not "title" in body and "detail" in body:
                body["title"] = body["detail"]
                del body["detail"]
                response.content = bytes(json.dumps(body, ensure_ascii=False), "utf-8")
        return response

    return middleware


def content_check(get_response_fn):
    "compares content-type in request against those that are supported."

    def middleware(request):
        request_accept_header = request.META.get("HTTP_ACCEPT", "*/*")

        # REST Framework will block unacceptable types up to a point.
        # it will not discriminate on the *value* of a parameter (like 'version')
        # this means, we can't automatically refuse version=1 of a particular mime
        # without rewriting or undermining a big chunk of their logic


# Path: src/publisher/utils.py
# def isint(v):
#     try:
#         int(v)
#         return True
#     except (ValueError, TypeError):
#         return False
# 
# Path: src/publisher/api_v2_views.py
# def flatten_accept(accepts_header_str):
#     "returns a list of triples like [(mime, 'version', version), ...]"
#     lst = []
#     if not accepts_header_str:
#         return lst
#     for mime in accepts_header_str.split(","):
#         # ('application/vnd.elife.article-vor+json', {'version': 2})
#         parsed_mime, parsed_params = parse_header(mime.encode())
#         # ('*/*', 'version', None)
#         # ('application/json', 'version', None)
#         # ('application/vnd.elife.article-poa+json', 'version', 2)
#         version = parsed_params.pop("version", b"").decode("utf-8")
#         lst.append((parsed_mime, "version", version or None))
#     return lst
# 
# def _ctype(content_type_key):
#     "returns a content type for the given `content_type_key`."
#     assert content_type_key in settings.CONTENT_TYPES
#     return "application/vnd.elife.article-%s+json" % content_type_key
# 
# def http_406():
#     "returns a HTTP 406 json error response (couldn't negotiate content type with request)."
#     title = "not acceptable"
#     detail = "could not negotiate an acceptable response type"
#     return error_response(406, title, detail)


# Path: src/publisher/middleware.py
from django.conf import settings
from .utils import isint
from .api_v2_views import flatten_accept, _ctype, http_406
import json
import logging

# todo: this middleware needs to go away and `error_response` in api_v2_views needs to
# emit responses valid against https://datatracker.ietf.org/doc/html/rfc7807 and
# https://github.com/elifesciences/api-raml/blob/develop/dist/model/error.v1.json
def error_content_check(get_response_fn):
    """This middleware ensures all unsuccessful responses have the correct structure."""

    def middleware(request):
        response = get_response_fn(request)
        if response.status_code > 399 and "json" in get_content_type(response):
            body = json.loads(response.content.decode("utf-8"))
            if not "title" in body and "detail" in body:
                body["title"] = body["detail"]
                del body["detail"]
                response.content = bytes(json.dumps(body, ensure_ascii=False), "utf-8")
        return response

    return middleware


def content_check(get_response_fn):
    "compares content-type in request against those that are supported."

    def middleware(request):
        request_accept_header = request.META.get("HTTP_ACCEPT", "*/*")

        # REST Framework will block unacceptable types up to a point.
        # it will not discriminate on the *value* of a parameter (like 'version')
        # this means, we can't automatically refuse version=1 of a particular mime
        # without rewriting or undermining a big chunk of their logic


        client_accepts_list = flatten_accept(request_accept_header)