from rest_framework.renderers import JSONRenderer as DRFJSONRenderer
from .response import JSONResponse
import logging

logger = logging.getLogger(__name__)


class JSONRenderer(DRFJSONRenderer):
    """
    自动统一返回结构
    """

    def render(self, data, accepted_media_type=None, renderer_context=None):

        # response 对象
        response = renderer_context.get("response")

        # data为空
        if data is None:
            data = JSONResponse().data

        # 如果不是标准结构，自动包装
        elif not isinstance(data, dict) or not all(
                k in data for k in ("code", "msg", "data")
        ):
            if isinstance(data, list):
                data = JSONResponse({"items": data}).data
            else:
                data = JSONResponse(data).data

        # 状态码和code不一致时记录日志
        if response:
            code = data.get("code", 0)
            if (code == 0 and response.status_code != 200) or (
                    code != 0 and response.status_code == 200
            ):
                logger.warning("response_code_mismatch", extra={"data": data})

        return super().render(data, accepted_media_type, renderer_context)
