# -*- coding: utf-8 -*-
from __future__ import annotations

import typing

from bthlabs_jsonrpc_django import (
    DjangoExecutor,
    DjangoJSONRPCSerializer,
    JSONRPCView as BaseJSONRPCView,
)
from django.core.exceptions import ValidationError
import uuid6


class JSONRPCSerializer(DjangoJSONRPCSerializer):
    STRING_COERCIBLE_TYPES: typing.Any = (
        *DjangoJSONRPCSerializer.STRING_COERCIBLE_TYPES,
        uuid6.UUID,
    )

    def serialize_value(self, value: typing.Any) -> typing.Any:
        if isinstance(value, ValidationError):
            result: typing.Any = None

            if hasattr(value, 'error_dict') is True:
                result = {}
                for field, errors in value.error_dict.items():
                    result[field] = [
                        error.code
                        for error
                        in errors
                    ]
            elif hasattr(value, 'error_list') is True:
                result = [
                    error.code
                    for error in value.error_list
                ]
            else:
                result = value.code

            return self.serialize_value(result)

        return super().serialize_value(value)


class Executor(DjangoExecutor):
    serializer = JSONRPCSerializer


class JSONRPCView(BaseJSONRPCView):
    executor = Executor
