from rest_framework import serializers
from iati.models import Narrative, DocumentCategory
from iati_synchroniser.models import Codelist
from api.generics.serializers import DynamicFieldsSerializer, DynamicFieldsModelSerializer
from django.core.urlresolvers import reverse


class VocabularySerializer(serializers.Serializer):
    code = serializers.CharField()
    name = serializers.CharField()


class CodelistSerializer(DynamicFieldsSerializer):
    code = serializers.CharField()
    name = serializers.CharField(required=False)


class CodelistCategorySerializer(CodelistSerializer):
    category = CodelistSerializer()


class CodelistVocabularySerializer(CodelistSerializer):
    vocabulary = VocabularySerializer()


class NarrativeSerializer(serializers.ModelSerializer):
    text = serializers.CharField(source="content")
    language = CodelistSerializer(required=False)

    class Meta:
        model = Narrative
        fields = (
            'text',
            'language',
        )

    # def validate(self, data):
    #     print('called validate...')


class NarrativeContainerSerializer(serializers.Serializer):
    narratives = NarrativeSerializer(many=True)


class DocumentCategorySerializer(serializers.ModelSerializer):
    class Meta:
        model = DocumentCategory
        fields = ('code', 'name')


class CodelistItemSerializer(DynamicFieldsModelSerializer):
    code = serializers.CharField()
    name = serializers.CharField(required=False)
    vocabulary = VocabularySerializer(required=False)
    category = CodelistSerializer(required=False)

    class Meta:
        model = None
        fields = ('code', 'name', 'vocabulary', 'category')


class CodelistMetaSerializer(DynamicFieldsModelSerializer):
    name = serializers.CharField()
    items = serializers.SerializerMethodField()

    def get_items(self, obj):
        request = self.context.get('request')
        url = request.build_absolute_uri(reverse('codelists:codelist-items-list', kwargs={'codelist': obj.name}))
        return url

    class Meta:
        model = Codelist
        fields = ('name', 'items')
@@ -345,32 +345,46 @@
 izers.CharField(
+required=False
 )%0A    name = ser
@@ -402,16 +402,30 @@
 arField(
+required=False
 )%0A%0A%0Aclas
@@ -496,32 +496,46 @@
 izers.CharField(
+required=False
 )%0A    name = ser
@@ -651,32 +651,46 @@
 elistSerializer(
+required=False
 )%0A%0A%0Aclass Codeli
@@ -729,24 +729,24 @@
 erializer):%0A
-
     vocabula
@@ -771,16 +771,30 @@
 ializer(
+required=False
 )%0A%0A%0Aclas
@@ -2170,8 +2170,9 @@
 'items')
+%0A

fix for API codelists not allowed to be null