"""
Group serializer
"""

from rest_framework import serializers

from core.apps.eggs import models
from core.apps.eggs.serializers import product


class GroupUserSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.User
        fields = (
            "id",
            "first_name",
            "last_name",
            "phone",
        )


class GroupPartySerializer(serializers.ModelSerializer):
    user = GroupUserSerializer(read_only=True, many=False, source="user_id")

    class Meta:
        model = models.Party
        fields = (
            "id",
            "user",
            "count",
            "sold_count",
            "remaining_count",
            "benefit",
            "cost",
            "total_cost",
        )


class GroupSerializer(serializers.ModelSerializer):
    party = GroupPartySerializer(read_only=True, many=False, source="party_id")
    product = product.ProductSerializer(
        read_only=True, many=False, source="product_id"
    )

    class Meta:
        model = models.Group
        fields = (
            "id",
            "name",
            "date",
            "entry_price",
            "unit_price",
            "wholesale_price",
            "quantity",
            "broken_eggs",
            "product",
            "party",
        )

    def update(self, instance, validated_data):
        instance.name = validated_data.get("name", instance.name)
        instance.date = validated_data.get("date", instance.date)
        instance.entry_price = validated_data.get(
            "entry_price", instance.entry_price
        )
        instance.unit_price = validated_data.get(
            "unit_price", instance.unit_price
        )
        instance.wholesale_price = validated_data.get(
            "wholesale_price", instance.wholesale_price
        )
        instance.quantity = validated_data.get("quantity", instance.quantity)
        instance.broken_eggs = validated_data.get(
            "broken_eggs", instance.broken_eggs
        )
        instance.save()
        return instance
