# coding: utf-8

"""
    Kubernetes

    No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)

    The version of the OpenAPI document: release-1.37
    Generated by OpenAPI Generator (https://openapi-generator.tech)

    Do not edit the class manually.
"""  # noqa: E501


from __future__ import annotations
import pprint
import re  # noqa: F401
import json

from collections.abc import Mapping as _Mapping
from pydantic import AliasChoices, BaseModel, ConfigDict, Field, StrictBool, StrictInt, StrictStr
from typing import Any, ClassVar, Dict, List, Optional, cast as _cast
from kubernetes.client.models.v1_container_state import V1ContainerState
from kubernetes.client.models.v1_container_user import V1ContainerUser
from kubernetes.client.models.v1_resource_requirements import V1ResourceRequirements
from kubernetes.client.models.v1_resource_status import V1ResourceStatus
from kubernetes.client.models.v1_volume_mount_status import V1VolumeMountStatus
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python


_OPENAPI_GENERATOR_TO_DICT = "_openapi_generator_to_dict"


def _get_openapi_to_dict(value: Any) -> Any:
    # Reciprocal function references preserve inherited generated methods
    # without reserving model member names. Checking both directions also
    # rejects overrides whose decorators copy function attributes.
    to_dict = getattr(value, "to_dict", None)
    type_to_dict = getattr(type(value), "to_dict", None)
    if (
        not callable(to_dict)
        or getattr(to_dict, "__func__", None) is not type_to_dict
    ):
        return None

    openapi_to_dict = getattr(
        type_to_dict, _OPENAPI_GENERATOR_TO_DICT, None
    )
    if (
        not callable(openapi_to_dict)
        or getattr(
            openapi_to_dict,
            _OPENAPI_GENERATOR_TO_DICT,
            None,
        ) is not type_to_dict
    ):
        return None
    return openapi_to_dict


def _to_legacy_item(value: Any, serialize: bool) -> Any:
    to_dict = getattr(value, "to_dict", None)
    if _get_openapi_to_dict(value) is not None and callable(to_dict):
        return to_dict(serialize=serialize)
    if callable(to_dict):
        return to_dict()
    return value


def _to_legacy_value(value: Any, serialize: bool) -> Any:
    # python-legacy converted only immediate list elements or dictionary values:
    # https://github.com/OpenAPITools/openapi-generator/blob/c84b949df1a9ec04ba75989cb49b45c940c2f694/modules/openapi-generator/src/main/resources/python-legacy/model.mustache#L203-L231
    if isinstance(value, list):
        return [_to_legacy_item(item, serialize) for item in value]
    if isinstance(value, dict):
        return {
            key: _to_legacy_item(item, serialize)
            for key, item in value.items()
        }
    return _to_legacy_item(value, serialize)


def _to_openapi_value(value: Any) -> Any:
    if isinstance(value, list):
        return [_to_openapi_value(item) for item in value]
    if isinstance(value, dict):
        return {key: _to_openapi_value(item) for key, item in value.items()}

    to_openapi_dict = _get_openapi_to_dict(value)
    if to_openapi_dict is not None:
        return to_openapi_dict(value)

    to_dict = getattr(value, "to_dict", None)
    if callable(to_dict):
        return to_dict()
    return value


class V1ContainerStatus(BaseModel):
    """
    ContainerStatus contains details for the current status of this container.

    Attributes:
      openapi_types (dict): The key is attribute name
                            and the value is attribute type.
      attribute_map (dict): The key is attribute name
                            and the value is json key in definition.
    """ # noqa: E501
    allocated_resources: Optional[Dict[str, StrictStr]] = Field(default=None, validation_alias=AliasChoices("allocatedResources", "allocated_resources"), serialization_alias="allocatedResources", description="AllocatedResources represents the compute resources allocated for this container by the node. Kubelet sets this value to Container.Resources.Requests upon successful pod admission and after successfully admitting desired pod resize.")
    allocated_resources_status: Optional[List[V1ResourceStatus]] = Field(default=None, validation_alias=AliasChoices("allocatedResourcesStatus", "allocated_resources_status"), serialization_alias="allocatedResourcesStatus", description="AllocatedResourcesStatus represents the status of various resources allocated for this Pod.")
    container_id: Optional[StrictStr] = Field(default=None, validation_alias=AliasChoices("containerID", "container_id"), serialization_alias="containerID", description="ContainerID is the ID of the container in the format '<type>://<container_id>'. Where type is a container runtime identifier, returned from Version call of CRI API (for example \"containerd\").")
    image: StrictStr = Field(description="Image is the name of container image that the container is running. The container image may not match the image used in the PodSpec, as it may have been resolved by the runtime. More info: https://kubernetes.io/docs/concepts/containers/images.")
    image_id: StrictStr = Field(validation_alias=AliasChoices("imageID", "image_id"), serialization_alias="imageID", description="ImageID is the image ID of the container's image. The image ID may not match the image ID of the image used in the PodSpec, as it may have been resolved by the runtime.")
    last_state: Optional[V1ContainerState] = Field(default=None, validation_alias=AliasChoices("lastState", "last_state"), serialization_alias="lastState")
    name: StrictStr = Field(description="Name is a DNS_LABEL representing the unique name of the container. Each container in a pod must have a unique name across all container types. Cannot be updated.")
    ready: StrictBool = Field(description="Ready specifies whether the container is currently passing its readiness check. The value will change as readiness probes keep executing. If no readiness probes are specified, this field defaults to true once the container is fully started (see Started field).  The value is typically used to determine whether a container is ready to accept traffic.")
    resources: Optional[V1ResourceRequirements] = None
    restart_count: StrictInt = Field(validation_alias=AliasChoices("restartCount", "restart_count"), serialization_alias="restartCount", description="RestartCount holds the number of times the container has been restarted. Kubelet makes an effort to always increment the value, but there are cases when the state may be lost due to node restarts and then the value may be reset to 0. The value is never negative.")
    started: Optional[StrictBool] = Field(default=None, description="Started indicates whether the container has finished its postStart lifecycle hook and passed its startup probe. Initialized as false, becomes true after startupProbe is considered successful. Resets to false when the container is restarted, or if kubelet loses state temporarily. In both cases, startup probes will run again. Is always true when no startupProbe is defined and container is running and has passed the postStart lifecycle hook. The null value must be treated the same as false.")
    state: Optional[V1ContainerState] = None
    stop_signal: Optional[StrictStr] = Field(default=None, validation_alias=AliasChoices("stopSignal", "stop_signal"), serialization_alias="stopSignal", description="StopSignal reports the effective stop signal for this container")
    user: Optional[V1ContainerUser] = None
    volume_mounts: Optional[List[V1VolumeMountStatus]] = Field(default=None, validation_alias=AliasChoices("volumeMounts", "volume_mounts"), serialization_alias="volumeMounts", description="Status of volume mounts.")
    openapi_types: ClassVar[Dict[str, str]] = {
        "allocated_resources": "Dict[str, str]",
        "allocated_resources_status": "List[V1ResourceStatus]",
        "container_id": "str",
        "image": "str",
        "image_id": "str",
        "last_state": "V1ContainerState",
        "name": "str",
        "ready": "bool",
        "resources": "V1ResourceRequirements",
        "restart_count": "int",
        "started": "bool",
        "state": "V1ContainerState",
        "stop_signal": "str",
        "user": "V1ContainerUser",
        "volume_mounts": "List[V1VolumeMountStatus]"
    }

    attribute_map: ClassVar[Dict[str, str]] = {
        "allocated_resources": "allocatedResources",
        "allocated_resources_status": "allocatedResourcesStatus",
        "container_id": "containerID",
        "image": "image",
        "image_id": "imageID",
        "last_state": "lastState",
        "name": "name",
        "ready": "ready",
        "resources": "resources",
        "restart_count": "restartCount",
        "started": "started",
        "state": "state",
        "stop_signal": "stopSignal",
        "user": "user",
        "volume_mounts": "volumeMounts"
    }
    __properties: ClassVar[List[str]] = ["allocatedResources", "allocatedResourcesStatus", "containerID", "image", "imageID", "lastState", "name", "ready", "resources", "restartCount", "started", "state", "stopSignal", "user", "volumeMounts"]

    @classmethod
    def __preprocess_input_names(
        cls,
        obj: Any,
        remove_hidden_storage_names: bool = True,
    ) -> Any:
        if not isinstance(obj, _Mapping):
            return obj
        obj = dict(obj)
        if "allocatedResources" not in obj and "allocated_resources" in obj:
            obj["allocatedResources"] = obj["allocated_resources"]
        obj.pop("allocated_resources", None)
        if "allocatedResourcesStatus" not in obj and "allocated_resources_status" in obj:
            obj["allocatedResourcesStatus"] = obj["allocated_resources_status"]
        obj.pop("allocated_resources_status", None)
        if "containerID" not in obj and "container_id" in obj:
            obj["containerID"] = obj["container_id"]
        obj.pop("container_id", None)
        if "imageID" not in obj and "image_id" in obj:
            obj["imageID"] = obj["image_id"]
        obj.pop("image_id", None)
        if "lastState" not in obj and "last_state" in obj:
            obj["lastState"] = obj["last_state"]
        obj.pop("last_state", None)
        if "restartCount" not in obj and "restart_count" in obj:
            obj["restartCount"] = obj["restart_count"]
        obj.pop("restart_count", None)
        if "stopSignal" not in obj and "stop_signal" in obj:
            obj["stopSignal"] = obj["stop_signal"]
        obj.pop("stop_signal", None)
        if "volumeMounts" not in obj and "volume_mounts" in obj:
            obj["volumeMounts"] = obj["volume_mounts"]
        obj.pop("volume_mounts", None)
        return obj

    model_config = ConfigDict(
        validate_by_name=True,
        validate_by_alias=True,
        validate_assignment=True,
        extra="forbid",
        protected_namespaces=(),
    )


    def to_str(self) -> str:
        """Returns the string representation of the model"""
        return pprint.pformat(self.to_dict())

    def __repr__(self) -> str:
        """For print and pprint"""
        return self.to_str()

    def __eq__(self, other: object) -> bool:
        """Returns true if both objects are equal"""
        if not isinstance(other, V1ContainerStatus):
            return False

        return self.to_dict() == other.to_dict()

    def __ne__(self, other: object) -> bool:
        """Returns true if both objects are not equal"""
        if not isinstance(other, V1ContainerStatus):
            return True

        return not (self == other)


    def to_json(self) -> str:
        """Returns the JSON representation of the model using alias"""
        to_openapi_dict = _get_openapi_to_dict(self)
        if to_openapi_dict is not None:
            return json.dumps(to_jsonable_python(to_openapi_dict(self)))
        return json.dumps(to_jsonable_python(self.to_dict()))

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

    def to_dict(self, serialize: bool = False) -> Dict[str, Any]:
        """Return all declared model fields using public or wire names."""
        return {
            ("allocatedResources" if serialize else "allocated_resources"): _to_legacy_value(getattr(self, "allocated_resources", None), serialize),
            ("allocatedResourcesStatus" if serialize else "allocated_resources_status"): _to_legacy_value(getattr(self, "allocated_resources_status", None), serialize),
            ("containerID" if serialize else "container_id"): _to_legacy_value(getattr(self, "container_id", None), serialize),
            ("image" if serialize else "image"): _to_legacy_value(getattr(self, "image", None), serialize),
            ("imageID" if serialize else "image_id"): _to_legacy_value(getattr(self, "image_id", None), serialize),
            ("lastState" if serialize else "last_state"): _to_legacy_value(getattr(self, "last_state", None), serialize),
            ("name" if serialize else "name"): _to_legacy_value(getattr(self, "name", None), serialize),
            ("ready" if serialize else "ready"): _to_legacy_value(getattr(self, "ready", None), serialize),
            ("resources" if serialize else "resources"): _to_legacy_value(getattr(self, "resources", None), serialize),
            ("restartCount" if serialize else "restart_count"): _to_legacy_value(getattr(self, "restart_count", None), serialize),
            ("started" if serialize else "started"): _to_legacy_value(getattr(self, "started", None), serialize),
            ("state" if serialize else "state"): _to_legacy_value(getattr(self, "state", None), serialize),
            ("stopSignal" if serialize else "stop_signal"): _to_legacy_value(getattr(self, "stop_signal", None), serialize),
            ("user" if serialize else "user"): _to_legacy_value(getattr(self, "user", None), serialize),
            ("volumeMounts" if serialize else "volume_mounts"): _to_legacy_value(getattr(self, "volume_mounts", None), serialize),
        }

    def __openapi_generator_modern_projection(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.
        """
        excluded_fields: Set[str] = set([
        ])

        _dict = self.model_dump(
            by_alias=True,
            exclude=excluded_fields,
            exclude_none=True,
        )
        # override the default output from pydantic by calling `to_dict()` of each item in allocated_resources_status (list)
        _items = []
        if self.allocated_resources_status:
            for _item_allocated_resources_status in self.allocated_resources_status:
                _items.append(_to_openapi_value(_item_allocated_resources_status) if _item_allocated_resources_status is not None else None)
            _dict['allocatedResourcesStatus'] = _items
        # override the default output from pydantic by calling `to_dict()` of last_state
        if self.last_state:
            _dict['lastState'] = _to_openapi_value(self.last_state)
        # override the default output from pydantic by calling `to_dict()` of resources
        if self.resources:
            _dict['resources'] = _to_openapi_value(self.resources)
        # override the default output from pydantic by calling `to_dict()` of state
        if self.state:
            _dict['state'] = _to_openapi_value(self.state)
        # override the default output from pydantic by calling `to_dict()` of user
        if self.user:
            _dict['user'] = _to_openapi_value(self.user)
        # override the default output from pydantic by calling `to_dict()` of each item in volume_mounts (list)
        _items = []
        if self.volume_mounts:
            for _item_volume_mounts in self.volume_mounts:
                _items.append(_to_openapi_value(_item_volume_mounts) if _item_volume_mounts is not None else None)
            _dict['volumeMounts'] = _items
        return _dict

    setattr(
        to_dict,
        _OPENAPI_GENERATOR_TO_DICT,
        __openapi_generator_modern_projection,
    )
    setattr(
        __openapi_generator_modern_projection,
        _OPENAPI_GENERATOR_TO_DICT,
        to_dict,
    )
    del __openapi_generator_modern_projection

    @classmethod
    def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
        """Create an instance of V1ContainerStatus from a dict"""
        if obj is None:
            return None

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

        obj = _cast(
            Dict[str, Any],
            cls.__preprocess_input_names(
                obj,
                remove_hidden_storage_names=True,
            ),
        )

        _obj = cls.model_validate({
            "allocatedResources": obj.get("allocatedResources"),
            "allocatedResourcesStatus": [V1ResourceStatus.from_dict(_item) for _item in obj["allocatedResourcesStatus"]] if obj.get("allocatedResourcesStatus") is not None else None,
            "containerID": obj.get("containerID"),
            "image": obj.get("image"),
            "imageID": obj.get("imageID"),
            "lastState": V1ContainerState.from_dict(obj["lastState"]) if obj.get("lastState") is not None else None,
            "name": obj.get("name"),
            "ready": obj.get("ready"),
            "resources": V1ResourceRequirements.from_dict(obj["resources"]) if obj.get("resources") is not None else None,
            "restartCount": obj.get("restartCount"),
            "started": obj.get("started"),
            "state": V1ContainerState.from_dict(obj["state"]) if obj.get("state") is not None else None,
            "stopSignal": obj.get("stopSignal"),
            "user": V1ContainerUser.from_dict(obj["user"]) if obj.get("user") is not None else None,
            "volumeMounts": [V1VolumeMountStatus.from_dict(_item) for _item in obj["volumeMounts"]] if obj.get("volumeMounts") is not None else None
        })
        return _obj
