# 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 datetime import datetime
from pydantic import AliasChoices, BaseModel, ConfigDict, Field, StrictInt, StrictStr
from typing import Any, ClassVar, Dict, List, Optional, cast as _cast
from kubernetes.aio.client.models.v1_job_condition import V1JobCondition
from kubernetes.aio.client.models.v1_uncounted_terminated_pods import V1UncountedTerminatedPods
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 V1JobStatus(BaseModel):
    """
    JobStatus represents the current state of a Job.

    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
    active: Optional[StrictInt] = Field(default=None, description="The number of pending and running pods which are not terminating (without a deletionTimestamp). The value is zero for finished jobs.")
    completed_indexes: Optional[StrictStr] = Field(default=None, validation_alias=AliasChoices("completedIndexes", "completed_indexes"), serialization_alias="completedIndexes", description="completedIndexes holds the completed indexes when .spec.completionMode = \"Indexed\" in a text format. The indexes are represented as decimal integers separated by commas. The numbers are listed in increasing order. Three or more consecutive numbers are compressed and represented by the first and last element of the series, separated by a hyphen. For example, if the completed indexes are 1, 3, 4, 5 and 7, they are represented as \"1,3-5,7\".")
    completion_time: Optional[datetime] = Field(default=None, validation_alias=AliasChoices("completionTime", "completion_time"), serialization_alias="completionTime", description="Represents time when the job was completed. It is not guaranteed to be set in happens-before order across separate operations. It is represented in RFC3339 form and is in UTC. The completion time is set when the job finishes successfully, and only then. The value cannot be updated or removed. The value indicates the same or later point in time as the startTime field.")
    conditions: Optional[List[V1JobCondition]] = Field(default=None, description="The latest available observations of an object's current state. When a Job fails, one of the conditions will have type \"Failed\" and status true. When a Job is suspended, one of the conditions will have type \"Suspended\" and status true; when the Job is resumed, the status of this condition will become false. When a Job is completed, one of the conditions will have type \"Complete\" and status true.  A job is considered finished when it is in a terminal condition, either \"Complete\" or \"Failed\". A Job cannot have both the \"Complete\" and \"Failed\" conditions. Additionally, it cannot be in the \"Complete\" and \"FailureTarget\" conditions. The \"Complete\", \"Failed\" and \"FailureTarget\" conditions cannot be disabled.  More info: https://kubernetes.io/docs/concepts/workloads/controllers/jobs-run-to-completion/")
    failed: Optional[StrictInt] = Field(default=None, description="The number of pods which reached phase Failed. The value increases monotonically.")
    failed_indexes: Optional[StrictStr] = Field(default=None, validation_alias=AliasChoices("failedIndexes", "failed_indexes"), serialization_alias="failedIndexes", description="FailedIndexes holds the failed indexes when spec.backoffLimitPerIndex is set. The indexes are represented in the text format analogous as for the `completedIndexes` field, ie. they are kept as decimal integers separated by commas. The numbers are listed in increasing order. Three or more consecutive numbers are compressed and represented by the first and last element of the series, separated by a hyphen. For example, if the failed indexes are 1, 3, 4, 5 and 7, they are represented as \"1,3-5,7\". The set of failed indexes cannot overlap with the set of completed indexes.")
    ready: Optional[StrictInt] = Field(default=None, description="The number of active pods which have a Ready condition and are not terminating (without a deletionTimestamp).")
    start_time: Optional[datetime] = Field(default=None, validation_alias=AliasChoices("startTime", "start_time"), serialization_alias="startTime", description="Represents time when the job controller started processing a job. When a Job is created in the suspended state, this field is not set until the first time it is resumed. This field is reset every time a Job is resumed from suspension. It is represented in RFC3339 form and is in UTC.  Once set, the field can only be removed when the job is suspended. The field cannot be modified while the job is unsuspended or finished.")
    succeeded: Optional[StrictInt] = Field(default=None, description="The number of pods which reached phase Succeeded. The value increases monotonically for a given spec. However, it may decrease in reaction to scale down of elastic indexed jobs.")
    terminating: Optional[StrictInt] = Field(default=None, description="The number of pods which are terminating (in phase Pending or Running and have a deletionTimestamp).")
    uncounted_terminated_pods: Optional[V1UncountedTerminatedPods] = Field(default=None, validation_alias=AliasChoices("uncountedTerminatedPods", "uncounted_terminated_pods"), serialization_alias="uncountedTerminatedPods")
    openapi_types: ClassVar[Dict[str, str]] = {
        "active": "int",
        "completed_indexes": "str",
        "completion_time": "datetime",
        "conditions": "List[V1JobCondition]",
        "failed": "int",
        "failed_indexes": "str",
        "ready": "int",
        "start_time": "datetime",
        "succeeded": "int",
        "terminating": "int",
        "uncounted_terminated_pods": "V1UncountedTerminatedPods"
    }

    attribute_map: ClassVar[Dict[str, str]] = {
        "active": "active",
        "completed_indexes": "completedIndexes",
        "completion_time": "completionTime",
        "conditions": "conditions",
        "failed": "failed",
        "failed_indexes": "failedIndexes",
        "ready": "ready",
        "start_time": "startTime",
        "succeeded": "succeeded",
        "terminating": "terminating",
        "uncounted_terminated_pods": "uncountedTerminatedPods"
    }
    __properties: ClassVar[List[str]] = ["active", "completedIndexes", "completionTime", "conditions", "failed", "failedIndexes", "ready", "startTime", "succeeded", "terminating", "uncountedTerminatedPods"]

    @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 "completedIndexes" not in obj and "completed_indexes" in obj:
            obj["completedIndexes"] = obj["completed_indexes"]
        obj.pop("completed_indexes", None)
        if "completionTime" not in obj and "completion_time" in obj:
            obj["completionTime"] = obj["completion_time"]
        obj.pop("completion_time", None)
        if "failedIndexes" not in obj and "failed_indexes" in obj:
            obj["failedIndexes"] = obj["failed_indexes"]
        obj.pop("failed_indexes", None)
        if "startTime" not in obj and "start_time" in obj:
            obj["startTime"] = obj["start_time"]
        obj.pop("start_time", None)
        if "uncountedTerminatedPods" not in obj and "uncounted_terminated_pods" in obj:
            obj["uncountedTerminatedPods"] = obj["uncounted_terminated_pods"]
        obj.pop("uncounted_terminated_pods", 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, V1JobStatus):
            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, V1JobStatus):
            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 V1JobStatus 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 {
            ("active" if serialize else "active"): _to_legacy_value(getattr(self, "active", None), serialize),
            ("completedIndexes" if serialize else "completed_indexes"): _to_legacy_value(getattr(self, "completed_indexes", None), serialize),
            ("completionTime" if serialize else "completion_time"): _to_legacy_value(getattr(self, "completion_time", None), serialize),
            ("conditions" if serialize else "conditions"): _to_legacy_value(getattr(self, "conditions", None), serialize),
            ("failed" if serialize else "failed"): _to_legacy_value(getattr(self, "failed", None), serialize),
            ("failedIndexes" if serialize else "failed_indexes"): _to_legacy_value(getattr(self, "failed_indexes", None), serialize),
            ("ready" if serialize else "ready"): _to_legacy_value(getattr(self, "ready", None), serialize),
            ("startTime" if serialize else "start_time"): _to_legacy_value(getattr(self, "start_time", None), serialize),
            ("succeeded" if serialize else "succeeded"): _to_legacy_value(getattr(self, "succeeded", None), serialize),
            ("terminating" if serialize else "terminating"): _to_legacy_value(getattr(self, "terminating", None), serialize),
            ("uncountedTerminatedPods" if serialize else "uncounted_terminated_pods"): _to_legacy_value(getattr(self, "uncounted_terminated_pods", 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 conditions (list)
        _items = []
        if self.conditions:
            for _item_conditions in self.conditions:
                _items.append(_to_openapi_value(_item_conditions) if _item_conditions is not None else None)
            _dict['conditions'] = _items
        # override the default output from pydantic by calling `to_dict()` of uncounted_terminated_pods
        if self.uncounted_terminated_pods:
            _dict['uncountedTerminatedPods'] = _to_openapi_value(self.uncounted_terminated_pods)
        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 V1JobStatus 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({
            "active": obj.get("active"),
            "completedIndexes": obj.get("completedIndexes"),
            "completionTime": obj.get("completionTime"),
            "conditions": [V1JobCondition.from_dict(_item) for _item in obj["conditions"]] if obj.get("conditions") is not None else None,
            "failed": obj.get("failed"),
            "failedIndexes": obj.get("failedIndexes"),
            "ready": obj.get("ready"),
            "startTime": obj.get("startTime"),
            "succeeded": obj.get("succeeded"),
            "terminating": obj.get("terminating"),
            "uncountedTerminatedPods": V1UncountedTerminatedPods.from_dict(obj["uncountedTerminatedPods"]) if obj.get("uncountedTerminatedPods") is not None else None
        })
        return _obj
