import json

from django import forms
from django.core.exceptions import ValidationError
from django.core.validators import validate_comma_separated_integer_list


class JsonValidator:

    def __init__(self, type):
        self.type = type

    def __call__(self, value):
        try:
            value = json.loads(value)
        except json.JSONDecodeError:
            raise ValidationError('invalid_json')
        else:
            if not isinstance(value, self.type):
                raise ValidationError('invalid_json_type')


class CommaSeparatedIntegerField(forms.CharField):

    default_validators = [validate_comma_separated_integer_list]


class JsonDictField(forms.CharField):

    default_validators = [JsonValidator(dict)]


class JsonListField(forms.CharField):

    default_validators = [JsonValidator(list)]
