# coding: utf-8

from collections import defaultdict

from django.utils.translation import gettext_lazy as _
from yarl import URL

from procu import jsonschema as js
from procu.api import models
from procu.rest import exceptions, serializers


class FilterField(serializers.JSONField):
    default_error_messages = {'invalid': _('FILTERFIELD::INVALID_FILTER')}

    def to_internal_value(self, data):

        url = URL(data)

        if not url.host:
            self.fail('invalid')

        params = defaultdict(list)
        for key, value in url.query.items():
            params[key].append(value)

        params.pop('limit', None)
        params.pop('page', None)

        return {'params': params, 'url': str(url)}

    def get_schema(self, *args, **kwargs):

        write = kwargs.get('write', False)

        if write:
            schema = js.String()
            schema['x-required'] = True
            schema['minLength'] = 1
            schema['maxLength'] = 2048
            return schema

        else:
            return super().get_schema(*args, **kwargs)


class Widget(serializers.ModelSerializer):
    check_for_nested_writes = False

    filter = FilterField()

    class Meta:
        model = models.DashboardWidget
        fields = ('id', 'name', 'limit', 'filter')

        extra_kwargs = {
            'limit': {'min_value': 1, 'max_value': 10000},
            'name': {'max_length': 255},
        }
