from __future__ import unicode_literals
from django.db import IntegrityError
from rest_framework.views import Response, exception_handler
from rest_framework import status
from itertools import islice


def custom_exception_handler(exc, context):
    # Call REST framework's default exception handler first,
    # to get the standard error response.
    response = exception_handler(exc, context)


    # Update the structure of the response data.
    if response is not None:
        print('dd')
        error_message = {}

        for key, value in response.data.items():
            print(value)
            if type(value) == list and value[0].code == 'blank':
                value = value[0].replace('This field', key)
            # elif type(value) == dict:
            #     value = value['non_field_errors']
            #     print(value['non_field_errors'])
            #     print("value['non_field_errors']")
            elif type(value) == list:
                value = value[0]

            error_message['code'] = response.status_code
            error_message['status'] = 'failed'
            error_message['message'] = value

        response.data = error_message
    return response
