# coding: utf-8

from django.utils import six
from django.utils.translation import gettext as _
from rest_framework import exceptions, views
from rest_framework.settings import api_settings


def stringify_error(data):

    if isinstance(data, list):
        return '; '.join(stringify_error(item) for item in data)

    elif isinstance(data, six.string_types):
        return data

    elif isinstance(data, dict):
        return ' '.join(map(stringify_error, data.items()))

    elif isinstance(data, tuple) and len(data) == 2:
        field, error = data

        if field == api_settings.NON_FIELD_ERRORS_KEY:
            return stringify_error(error)

        else:
            return '[%s]: %s' % (field, stringify_error(error))

    else:
        return '[Unknown error object]'


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

    if isinstance(exc, exceptions.NotAuthenticated):
        response.data['detail'] = _('AUTH::AUTHENTICATION_REQUIRED')
        response.data['error_code'] = 'AUTHENTICATION_REQUIRED'

    if isinstance(exc, exceptions.ValidationError):

        if isinstance(response.data, list):
            data = response.data
        elif isinstance(response.data, dict):
            data = [response.data]
        else:
            return response

        for item in data:
            if isinstance(item, dict) and 'detail' not in item:
                item['detail'] = stringify_error(item)

    return response


class ValidationError(exceptions.ValidationError):
    def __init__(self, detail, code=None):

        if not isinstance(detail, dict):
            detail = {'detail': detail}

        super().__init__(detail, code=code)
