from rest_framework import serializers

import recipe.models
from utils import const


class IngredientSerializer(serializers.ModelSerializer):
    id = serializers.IntegerField(read_only=True)

    class Meta:
        model = recipe.models.Ingredient
        fields = '__all__'


class RecipeIngredientSerializer(serializers.ModelSerializer):
    id = serializers.IntegerField(read_only=True)
    ingredient = IngredientSerializer()

    def update(self, instance, validated_data):
        if 'ingredient' in validated_data:
            validated_data.pop('ingredient')
        if 'recipe' in validated_data:
            validated_data.pop('recipe')
        return super().update(instance, validated_data)

    class Meta:
        model = recipe.models.RecipeIngredient
        fields = '__all__'


class RecipeSerializer(serializers.ModelSerializer):
    id = serializers.IntegerField(read_only=True)
    recipe_ingredients = RecipeIngredientSerializer(many=True, read_only=True)

    def create(self, validated_data):
        if 'recipe_ingredients' in validated_data:
            recipe_ingredients = validated_data.pop('recipe_ingredients')
        instance = super().create(validated_data)
        if recipe_ingredients:
            for recipe_ingredient in recipe_ingredients:
                recipe_ingredient['recipe'] = instance
                RecipeIngredientSerializer.create(recipe_ingredient)
        return instance

    @property
    def data(self):
        # exclude deleted recipe_ingredients
        data_ = super().data
        data_['recipe_ingredients'] = [
            ingredient
            for ingredient in data_['recipe_ingredients']
            if ingredient['status'] != const.INGREDIENT_STATUS_DELETED
        ]
        return data_

    class Meta:
        model = recipe.models.Recipe
        fields = ('recipe_ingredients', 'id', 'name', 'recipe_type', 'status', 'note', 'rate', 'difficulty')


class WeekRecipeSerializer(serializers.ModelSerializer):
    class Meta:
        model = recipe.models.DailyRecipe
        fields = '__all__'


class DailyRecipeSerializer(serializers.ModelSerializer):
    id = serializers.IntegerField(read_only=True)
    recipes = RecipeSerializer(many=True)

    class Meta:
        model = recipe.models.DailyRecipe
        fields = '__all__'
