from __future__ import annotations

import datetime
import json
from collections.abc import Mapping
from typing import TYPE_CHECKING, Any, TypeVar, cast

from attrs import define as _attrs_define
from attrs import field as _attrs_field
from dateutil.parser import isoparse

from .. import types
from ..types import UNSET, Unset

if TYPE_CHECKING:
    from ..models.food_shopping import FoodShopping
    from ..models.shopping_list import ShoppingList
    from ..models.shopping_list_recipe import ShoppingListRecipe
    from ..models.unit import Unit
    from ..models.user import User


T = TypeVar("T", bound="ShoppingListEntry")


@_attrs_define
class ShoppingListEntry:
    """Adds nested create feature

    Attributes:
        food (FoodShopping | None):
        amount (float):
        list_recipe_data (ShoppingListRecipe):
        created_by (User): Adds nested create feature
        created_at (datetime.datetime):
        updated_at (datetime.datetime):
        id (int | Unset):
        list_recipe (int | None | Unset):
        shopping_lists (list[ShoppingList] | Unset):
        unit (None | Unit | Unset):
        order (int | Unset):
        checked (bool | Unset):
        ingredient (int | None | Unset):
        completed_at (datetime.datetime | None | Unset):
        delay_until (datetime.datetime | None | Unset):
        mealplan_id (int | Unset): If a mealplan id is given try to find existing or create new ShoppingListRecipe with
            that meal plan and link entry to it
    """

    food: FoodShopping | None
    amount: float
    list_recipe_data: ShoppingListRecipe
    created_by: User
    created_at: datetime.datetime
    updated_at: datetime.datetime
    id: int | Unset = UNSET
    list_recipe: int | None | Unset = UNSET
    shopping_lists: list[ShoppingList] | Unset = UNSET
    unit: None | Unit | Unset = UNSET
    order: int | Unset = UNSET
    checked: bool | Unset = UNSET
    ingredient: int | None | Unset = UNSET
    completed_at: datetime.datetime | None | Unset = UNSET
    delay_until: datetime.datetime | None | Unset = UNSET
    mealplan_id: int | Unset = UNSET
    additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)

    def to_dict(self) -> dict[str, Any]:
        from ..models.food_shopping import FoodShopping
        from ..models.unit import Unit

        food: dict[str, Any] | None
        if isinstance(self.food, FoodShopping):
            food = self.food.to_dict()
        else:
            food = self.food

        amount = self.amount

        list_recipe_data = self.list_recipe_data.to_dict()

        created_by = self.created_by.to_dict()

        created_at = self.created_at.isoformat()

        updated_at = self.updated_at.isoformat()

        id = self.id

        list_recipe: int | None | Unset
        if isinstance(self.list_recipe, Unset):
            list_recipe = UNSET
        else:
            list_recipe = self.list_recipe

        shopping_lists: list[dict[str, Any]] | Unset = UNSET
        if not isinstance(self.shopping_lists, Unset):
            shopping_lists = []
            for shopping_lists_item_data in self.shopping_lists:
                shopping_lists_item = shopping_lists_item_data.to_dict()
                shopping_lists.append(shopping_lists_item)

        unit: dict[str, Any] | None | Unset
        if isinstance(self.unit, Unset):
            unit = UNSET
        elif isinstance(self.unit, Unit):
            unit = self.unit.to_dict()
        else:
            unit = self.unit

        order = self.order

        checked = self.checked

        ingredient: int | None | Unset
        if isinstance(self.ingredient, Unset):
            ingredient = UNSET
        else:
            ingredient = self.ingredient

        completed_at: None | str | Unset
        if isinstance(self.completed_at, Unset):
            completed_at = UNSET
        elif isinstance(self.completed_at, datetime.datetime):
            completed_at = self.completed_at.isoformat()
        else:
            completed_at = self.completed_at

        delay_until: None | str | Unset
        if isinstance(self.delay_until, Unset):
            delay_until = UNSET
        elif isinstance(self.delay_until, datetime.datetime):
            delay_until = self.delay_until.isoformat()
        else:
            delay_until = self.delay_until

        mealplan_id = self.mealplan_id

        field_dict: dict[str, Any] = {}
        field_dict.update(self.additional_properties)
        field_dict.update(
            {
                "food": food,
                "amount": amount,
                "list_recipe_data": list_recipe_data,
                "created_by": created_by,
                "created_at": created_at,
                "updated_at": updated_at,
            }
        )
        if id is not UNSET:
            field_dict["id"] = id
        if list_recipe is not UNSET:
            field_dict["list_recipe"] = list_recipe
        if shopping_lists is not UNSET:
            field_dict["shopping_lists"] = shopping_lists
        if unit is not UNSET:
            field_dict["unit"] = unit
        if order is not UNSET:
            field_dict["order"] = order
        if checked is not UNSET:
            field_dict["checked"] = checked
        if ingredient is not UNSET:
            field_dict["ingredient"] = ingredient
        if completed_at is not UNSET:
            field_dict["completed_at"] = completed_at
        if delay_until is not UNSET:
            field_dict["delay_until"] = delay_until
        if mealplan_id is not UNSET:
            field_dict["mealplan_id"] = mealplan_id

        return field_dict

    def to_multipart(self) -> types.RequestFiles:
        files: types.RequestFiles = []

        if self.food is None:
            files.append(("food", (None, str(self.food).encode(), "text/plain")))
        else:
            files.append(("food", (None, json.dumps(self.food.to_dict()).encode(), "application/json")))

        files.append(("amount", (None, str(self.amount).encode(), "text/plain")))

        files.append(
            ("list_recipe_data", (None, json.dumps(self.list_recipe_data.to_dict()).encode(), "application/json"))
        )

        files.append(("created_by", (None, json.dumps(self.created_by.to_dict()).encode(), "application/json")))

        files.append(("created_at", (None, self.created_at.isoformat().encode(), "text/plain")))

        files.append(("updated_at", (None, self.updated_at.isoformat().encode(), "text/plain")))

        if not isinstance(self.id, Unset):
            files.append(("id", (None, str(self.id).encode(), "text/plain")))

        if not isinstance(self.list_recipe, Unset):
            if isinstance(self.list_recipe, int):
                files.append(("list_recipe", (None, str(self.list_recipe).encode(), "text/plain")))
            else:
                files.append(("list_recipe", (None, str(self.list_recipe).encode(), "text/plain")))

        if not isinstance(self.shopping_lists, Unset):
            for shopping_lists_item_element in self.shopping_lists:
                files.append(
                    (
                        "shopping_lists",
                        (None, json.dumps(shopping_lists_item_element.to_dict()).encode(), "application/json"),
                    )
                )

        if not isinstance(self.unit, Unset):
            if self.unit is None:
                files.append(("unit", (None, str(self.unit).encode(), "text/plain")))
            else:
                files.append(("unit", (None, json.dumps(self.unit.to_dict()).encode(), "application/json")))

        if not isinstance(self.order, Unset):
            files.append(("order", (None, str(self.order).encode(), "text/plain")))

        if not isinstance(self.checked, Unset):
            files.append(("checked", (None, str(self.checked).encode(), "text/plain")))

        if not isinstance(self.ingredient, Unset):
            if isinstance(self.ingredient, int):
                files.append(("ingredient", (None, str(self.ingredient).encode(), "text/plain")))
            else:
                files.append(("ingredient", (None, str(self.ingredient).encode(), "text/plain")))

        if not isinstance(self.completed_at, Unset):
            if isinstance(self.completed_at, datetime.datetime):
                files.append(("completed_at", (None, self.completed_at.isoformat().encode(), "text/plain")))
            else:
                files.append(("completed_at", (None, str(self.completed_at).encode(), "text/plain")))

        if not isinstance(self.delay_until, Unset):
            if isinstance(self.delay_until, datetime.datetime):
                files.append(("delay_until", (None, self.delay_until.isoformat().encode(), "text/plain")))
            else:
                files.append(("delay_until", (None, str(self.delay_until).encode(), "text/plain")))

        if not isinstance(self.mealplan_id, Unset):
            files.append(("mealplan_id", (None, str(self.mealplan_id).encode(), "text/plain")))

        for prop_name, prop in self.additional_properties.items():
            files.append((prop_name, (None, str(prop).encode(), "text/plain")))

        return files

    @classmethod
    def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
        from ..models.food_shopping import FoodShopping
        from ..models.shopping_list import ShoppingList
        from ..models.shopping_list_recipe import ShoppingListRecipe
        from ..models.unit import Unit
        from ..models.user import User

        d = dict(src_dict)

        def _parse_food(data: object) -> FoodShopping | None:
            if data is None:
                return data
            try:
                if not isinstance(data, dict):
                    raise TypeError()
                food_type_1 = FoodShopping.from_dict(data)

                return food_type_1
            except (TypeError, ValueError, AttributeError, KeyError):
                pass
            return cast(FoodShopping | None, data)

        food = _parse_food(d.pop("food"))

        amount = d.pop("amount")

        list_recipe_data = ShoppingListRecipe.from_dict(d.pop("list_recipe_data"))

        created_by = User.from_dict(d.pop("created_by"))

        created_at = isoparse(d.pop("created_at"))

        updated_at = isoparse(d.pop("updated_at"))

        id = d.pop("id", UNSET)

        def _parse_list_recipe(data: object) -> int | None | Unset:
            if data is None:
                return data
            if isinstance(data, Unset):
                return data
            return cast(int | None | Unset, data)

        list_recipe = _parse_list_recipe(d.pop("list_recipe", UNSET))

        _shopping_lists = d.pop("shopping_lists", UNSET)
        shopping_lists: list[ShoppingList] | Unset = UNSET
        if _shopping_lists is not UNSET:
            shopping_lists = []
            for shopping_lists_item_data in _shopping_lists:
                shopping_lists_item = ShoppingList.from_dict(shopping_lists_item_data)

                shopping_lists.append(shopping_lists_item)

        def _parse_unit(data: object) -> None | Unit | Unset:
            if data is None:
                return data
            if isinstance(data, Unset):
                return data
            try:
                if not isinstance(data, dict):
                    raise TypeError()
                unit_type_1 = Unit.from_dict(data)

                return unit_type_1
            except (TypeError, ValueError, AttributeError, KeyError):
                pass
            return cast(None | Unit | Unset, data)

        unit = _parse_unit(d.pop("unit", UNSET))

        order = d.pop("order", UNSET)

        checked = d.pop("checked", UNSET)

        def _parse_ingredient(data: object) -> int | None | Unset:
            if data is None:
                return data
            if isinstance(data, Unset):
                return data
            return cast(int | None | Unset, data)

        ingredient = _parse_ingredient(d.pop("ingredient", UNSET))

        def _parse_completed_at(data: object) -> datetime.datetime | None | Unset:
            if data is None:
                return data
            if isinstance(data, Unset):
                return data
            try:
                if not isinstance(data, str):
                    raise TypeError()
                completed_at_type_0 = isoparse(data)

                return completed_at_type_0
            except (TypeError, ValueError, AttributeError, KeyError):
                pass
            return cast(datetime.datetime | None | Unset, data)

        completed_at = _parse_completed_at(d.pop("completed_at", UNSET))

        def _parse_delay_until(data: object) -> datetime.datetime | None | Unset:
            if data is None:
                return data
            if isinstance(data, Unset):
                return data
            try:
                if not isinstance(data, str):
                    raise TypeError()
                delay_until_type_0 = isoparse(data)

                return delay_until_type_0
            except (TypeError, ValueError, AttributeError, KeyError):
                pass
            return cast(datetime.datetime | None | Unset, data)

        delay_until = _parse_delay_until(d.pop("delay_until", UNSET))

        mealplan_id = d.pop("mealplan_id", UNSET)

        shopping_list_entry = cls(
            food=food,
            amount=amount,
            list_recipe_data=list_recipe_data,
            created_by=created_by,
            created_at=created_at,
            updated_at=updated_at,
            id=id,
            list_recipe=list_recipe,
            shopping_lists=shopping_lists,
            unit=unit,
            order=order,
            checked=checked,
            ingredient=ingredient,
            completed_at=completed_at,
            delay_until=delay_until,
            mealplan_id=mealplan_id,
        )

        shopping_list_entry.additional_properties = d
        return shopping_list_entry

    @property
    def additional_keys(self) -> list[str]:
        return list(self.additional_properties.keys())

    def __getitem__(self, key: str) -> Any:
        return self.additional_properties[key]

    def __setitem__(self, key: str, value: Any) -> None:
        self.additional_properties[key] = value

    def __delitem__(self, key: str) -> None:
        del self.additional_properties[key]

    def __contains__(self, key: str) -> bool:
        return key in self.additional_properties
