from rest_framework.response import Response as DRFResponse
from rest_framework.views import exception_handler as DRF_exception_handler


class Response(DRFResponse):
    def __init__(self, data=None, *args, **kwargs):
        if data and 'err' not in data:
            data['err'] = 0
        super().__init__(data, *args, **kwargs)


class APIError(Exception):
    http_status = 200

    def __init__(self, message, err=1, errors=None):
        self.err_desc = message
        self.err = err
        self.errors = errors
        super().__init__(self.err_desc)

    def to_response(self):
        data = {
            'err': self.err,
            'err_class': self.err_desc,
            'err_desc': self.err_desc,
        }
        if self.errors:
            data['errors'] = self.errors
        return Response(data, status=self.http_status)


class APIErrorBadRequest(APIError):
    http_status = 400


def exception_handler(exc, context):
    if isinstance(exc, APIError):
        return exc.to_response()

    return DRF_exception_handler(exc, context)
