from rest_framework import serializers


class DynamicFieldsModelSerializer(serializers.ModelSerializer):
    """
    A ModelSerializer that takes an additional `fields` argument that
    controls which fields should be displayed.
    """

    def __init__(self, *args, **kwargs):
        # Don't pass the 'fields' arg up to the superclass
        fields = kwargs.pop('fields', None)
        exclude = kwargs.pop('exclude', None)

        # Instantiate the superclass normally
        super(DynamicFieldsModelSerializer, self).__init__(*args, **kwargs)

        if fields is not None:
            # Drop any fields that are not specified in the `fields` argument.
            allowed = set(fields)
            existing = set(self.fields)
            for field_name in existing - allowed:
                self.fields.pop(field_name)

        if exclude:
            # Drop fields that are specified in the `exclude` argument.
            excluded = set(exclude)
            for field_name in excluded:
                try:
                    self.fields.pop(field_name)
                except KeyError:
                    pass


class ReviewsCountRep:
    def to_representation(self, instance):
        rep = super().to_representation(instance)
        if (
            hasattr(instance, 'cal_reviews_count')
            and rep.get('reviews_count', None) is None
        ):
            rep['reviews_count'] = instance.cal_reviews_count
        return rep


class AverageRatingRep:
    def to_representation(self, instance):
        rep = super().to_representation(instance)
        if (
            hasattr(instance, 'cal_average_rating')
            and rep.get('average_rating', None) is None
        ):
            rep['average_rating'] = instance.cal_average_rating

        return rep
