# coding: utf-8
"""统一响应"""
import logging

from rest_framework.response import Response
from rest_framework import status, serializers
from .return_structure import error_message

logger = logging.getLogger("")


def custom_exception_handler(exc, context):
    """
        Returns the response that should be used for any given exception.

        By default we handle the REST framework `APIException`, and also
        Django's built-in `Http404` and `PermissionDenied` exceptions.

        Any unhandled exceptions may return `None`, which will cause a 500
        error to be raised.
    """
    if isinstance(exc, NoFoundNumber):
        return exc.response
    elif isinstance(exc, serializers.ValidationError):
        logger.exception(exc)
        data = error_message(msg="json data not valid")
        return Response(data, status=status.HTTP_400_BAD_REQUEST)
    else:
        logger.exception(exc)
        if hasattr(exc, "message"):
            msg = str(exc.message)
        else:
            msg = str(exc)
        data = error_message(msg=msg)
        return Response(data, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class MessageResponse(Response):
    """统一响应"""
    def __init__(self, msg, code):
        """
        :param msg: 响应信息(中文)
        """
        body = {"msg": msg}
        status_code = 400
        super(MessageResponse, self).__init__(data=body, status=status_code)


class ServiceHandleException(Exception):
    def __init__(self, msg, code):
        """
        :param msg: 错误信息(英文)
        """
        super(Exception, self).__init__(msg)
        self.msg = msg
        self.code = code

    @property
    def response(self):
        return MessageResponse(msg=self.msg)


class NoFoundNumber(ServiceHandleException):
    def __init__(self):
        super(NoFoundNumber, self).__init__("sn not valid", 400)
