from rest_framework import serializers
from apps.livestock import models as livestock_models
from apps.herd.web.api.v1.serializers import HerdSerializer
from apps.tag.web.api.v1.serializers import TagSerializer


class LiveStockTypeSerializer(serializers.ModelSerializer):
    class Meta:
        model = livestock_models.LiveStockType
        fields = [
            'id',
            'name',
            'weight_type'
        ]


class LiveStockUseTypeSerializer(serializers.ModelSerializer):
    class Meta:
        model = livestock_models.LiveStockUseType
        fields = [
            'id',
            'name'
        ]


class LiveStockSpeciesSerializer(serializers.ModelSerializer):
    class Meta:
        model = livestock_models.LiveStockSpecies
        fields = [
            'id',
            'name'
        ]


class LiveStockSerializer(serializers.ModelSerializer):
    """ livestock serializer """

    class Meta:
        model = livestock_models.LiveStock
        fields = [
            'id',
            'herd',
            'tag',
            'type',
            'use_type',
            'weight_type',
            'species',
            'birthdate',
            'gender',
        ]

    def to_representation(self, instance):
        """ Customize output of serializer """
        representation = super().to_representation(instance)
        if isinstance(instance, livestock_models.LiveStock):
            representation['herd'] = HerdSerializer(instance.herd).data
            representation['tag'] = TagSerializer(instance.tag).data
            representation['type'] = LiveStockTypeSerializer(instance.type).data
            representation['use_type'] = LiveStockUseTypeSerializer(instance.use_type).data
            representation['species'] = LiveStockSpeciesSerializer(instance.species).data

        return representation
