from rest_framework import serializers

from verify_trusted.companies.models import Review
from verify_trusted.reviews.api.serializers import ReviewSourceSerializer
from verify_trusted.widgets.models import Seal, Widget


class ReviewWidgetSerializer(serializers.ModelSerializer):
    id = serializers.IntegerField()
    source = ReviewSourceSerializer()

    class Meta:
        model = Review
        fields = "__all__"


class WidgetSerializer(serializers.ModelSerializer):
    reviews = ReviewWidgetSerializer(many=True, required=False)

    class Meta:
        model = Widget
        fields = '__all__'

    def create(self, validated_data):
        reviews = []
        if 'reviews' in validated_data and len(validated_data['reviews']) > 0:
            for i in validated_data['reviews']:
                get_review = Review.objects.filter(pk=i['id']).first()
                if get_review is not None:
                    reviews.append(get_review)
        validated_data.pop('reviews', None)
        widget = super().create(validated_data)
        if len(reviews) > 0:
            # reviews = Review.objects.all().order_by('-rating')[:5]
            widget.reviews.add(*reviews)
        return widget

    def update(self, instance, validated_data):
        review_data = validated_data.pop('reviews', None)
        if review_data is not None:
            instance.reviews.clear()
            for id in review_data:
                review_qs = Review.objects.filter(id=id['id'])
                if review_qs is not None:
                    review = review_qs.first()
                    instance.reviews.add(review)
        return super().update(instance, validated_data)

    def validate(self, data):
        super().validate(data)
        return data


class WidgetDemoSerializer(serializers.ModelSerializer):
    source = ReviewSourceSerializer(read_only=True)

    class Meta:
        model = Widget
        fields = '__all__'


class SealSerializer(serializers.ModelSerializer):
    class Meta:
        model = Seal
        fields = '__all__'
