"""
Market serializer
"""

from rest_framework import serializers

from core.apps.eggs import models
from core.apps.eggs.serializers import location, order
from core.http.serializers import user


class MarketSerializer(serializers.ModelSerializer):
    user = user.UserSerializer(source="user_id", read_only=True)
    location = location.LocationSerializer(source="location_id")

    class Meta:
        model = models.Market
        fields = (
            "id",
            "name",
            "company_name",
            "user_id",
            "avatar",
            "user",
            "phone",
            "location",
            "debt_paid",
            "debt_unpaid",
        )
        extra_kwargs = {
            "user_id": {"write_only": True},
        }

    def create(self, validated_data):
        user_id = validated_data.pop("user_id")
        location_data = validated_data.pop("location_id")

        location = models.Location.objects.create(**location_data)

        market = models.Market.objects.create(
            user_id=user_id, location_id=location, **validated_data
        )

        return market

    def update(self, instance, validated_data):
        location_data = validated_data.pop("location_id", None)

        if location_data:
            for attr, value in location_data.items():
                setattr(instance.location_id, attr, value)
            instance.location_id.save()

        for attr, value in validated_data.items():
            setattr(instance, attr, value)

        instance.save()
        return instance


class MarketHistorySerializer(serializers.ModelSerializer):
    user = user.UserSerializer(read_only=True, source="user_id")
    location = location.LocationSerializer(
        read_only=True, source="location_id"
    )
    orders = serializers.SerializerMethodField()

    class Meta:
        model = models.Market
        fields = (
            "id",
            "name",
            "company_name",
            "user_id",
            "avatar",
            "user",
            "phone",
            "location",
            "orders",
            "debt_paid",
            "debt_unpaid",
        )

    def get_orders(self, obj):
        orders = models.Order.objects.filter(market_id=obj.id)
        serializer = order.OrderSerializer(orders, many=True)
        return serializer.data
