# coding: utf-8

"""
Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT.
"""
from __future__ import annotations

from json import loads
from typing import Any, Dict, List, Optional, Self

from pydantic import BaseModel, Field, StrictBool, StrictStr

from algoliasearch.search.models.condition import Condition
from algoliasearch.search.models.consequence import Consequence
from algoliasearch.search.models.time_range import TimeRange


class Rule(BaseModel):
    """
    Rule object.
    """

    object_id: StrictStr = Field(
        description="Unique identifier for a rule object.", alias="objectID"
    )
    conditions: Optional[List[Condition]] = Field(
        default=None,
        description="[Conditions](https://www.algolia.com/doc/guides/managing-results/rules/rules-overview/#conditions) required to activate a rule. You can use up to 25 conditions per rule. ",
    )
    consequence: Optional[Consequence] = None
    description: Optional[StrictStr] = Field(
        default=None,
        description="Description of the rule's purpose. This can be helpful for display in the Algolia dashboard.",
    )
    enabled: Optional[StrictBool] = Field(
        default=True,
        description="Indicates whether to enable the rule. If it isn't enabled, it isn't applied at query time.",
    )
    validity: Optional[List[TimeRange]] = Field(
        default=None,
        description="If you specify a validity period, the rule _only_ applies only during that period. If specified, the array must not be empty.",
    )

    model_config = {"populate_by_name": True, "validate_assignment": True}

    def to_json(self) -> str:
        return self.model_dump_json(by_alias=True, exclude_unset=True)

    @classmethod
    def from_json(cls, json_str: str) -> Self:
        """Create an instance of Rule from a JSON string"""
        return cls.from_dict(loads(json_str))

    def to_dict(self) -> Dict[str, Any]:
        """Return the dictionary representation of the model using alias.

        This has the following differences from calling pydantic's
        `self.model_dump(by_alias=True)`:

        * `None` is only added to the output dict for nullable fields that
          were set at model initialization. Other fields with value `None`
          are ignored.
        """
        _dict = self.model_dump(
            by_alias=True,
            exclude={},
            exclude_none=True,
        )
        # override the default output from pydantic by calling `to_dict()` of
        # each item in conditions (list)
        _items = []
        if self.conditions:
            for _item in self.conditions:
                if _item:
                    _items.append(_item.to_dict())
            _dict["conditions"] = _items
        # override the default output from pydantic by calling `to_dict()` of
        # consequence
        if self.consequence:
            _dict["consequence"] = self.consequence.to_dict()
        # override the default output from pydantic by calling `to_dict()` of
        # each item in validity (list)
        _items = []
        if self.validity:
            for _item in self.validity:
                if _item:
                    _items.append(_item.to_dict())
            _dict["validity"] = _items
        return _dict

    @classmethod
    def from_dict(cls, obj: Dict) -> Self:
        """Create an instance of Rule from a dict"""
        if obj is None:
            return None

        if not isinstance(obj, dict):
            return cls.model_validate(obj)

        _obj = cls.model_validate(
            {
                "objectID": obj.get("objectID"),
                "conditions": [
                    Condition.from_dict(_item) for _item in obj.get("conditions")
                ]
                if obj.get("conditions") is not None
                else None,
                "consequence": Consequence.from_dict(obj.get("consequence"))
                if obj.get("consequence") is not None
                else None,
                "description": obj.get("description"),
                "enabled": obj.get("enabled")
                if obj.get("enabled") is not None
                else True,
                "validity": [
                    TimeRange.from_dict(_item) for _item in obj.get("validity")
                ]
                if obj.get("validity") is not None
                else None,
            }
        )
        return _obj
