# 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.events_v1_event_series import EventsV1EventSeries
from kubernetes.aio.client.models.v1_event_source import V1EventSource
from kubernetes.aio.client.models.v1_object_meta import V1ObjectMeta
from kubernetes.aio.client.models.v1_object_reference import V1ObjectReference
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 EventsV1Event(BaseModel):
    """
    Event is a report of an event somewhere in the cluster. It generally denotes some state change in the system. Events have a limited retention time and triggers and messages may evolve with time.  Event consumers should not rely on the timing of an event with a given Reason reflecting a consistent underlying trigger, or the continued existence of events with that Reason.  Events should be treated as informative, best-effort, supplemental data.

    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
    action: Optional[StrictStr] = Field(default=None, description="action is what action was taken/failed regarding to the regarding object. It is machine-readable. This field cannot be empty for new Events and it can have at most 128 characters.")
    api_version: Optional[StrictStr] = Field(default=None, validation_alias=AliasChoices("apiVersion", "api_version"), serialization_alias="apiVersion", description="APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources")
    deprecated_count: Optional[StrictInt] = Field(default=None, validation_alias=AliasChoices("deprecatedCount", "deprecated_count"), serialization_alias="deprecatedCount", description="deprecatedCount is the deprecated field assuring backward compatibility with core.v1 Event type.")
    deprecated_first_timestamp: Optional[datetime] = Field(default=None, validation_alias=AliasChoices("deprecatedFirstTimestamp", "deprecated_first_timestamp"), serialization_alias="deprecatedFirstTimestamp", description="deprecatedFirstTimestamp is the deprecated field assuring backward compatibility with core.v1 Event type.")
    deprecated_last_timestamp: Optional[datetime] = Field(default=None, validation_alias=AliasChoices("deprecatedLastTimestamp", "deprecated_last_timestamp"), serialization_alias="deprecatedLastTimestamp", description="deprecatedLastTimestamp is the deprecated field assuring backward compatibility with core.v1 Event type.")
    deprecated_source: Optional[V1EventSource] = Field(default=None, validation_alias=AliasChoices("deprecatedSource", "deprecated_source"), serialization_alias="deprecatedSource")
    event_time: datetime = Field(validation_alias=AliasChoices("eventTime", "event_time"), serialization_alias="eventTime", description="eventTime is the time when this Event was first observed. It is required.")
    kind: Optional[StrictStr] = Field(default=None, description="Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds")
    metadata: Optional[V1ObjectMeta] = None
    note: Optional[StrictStr] = Field(default=None, description="note is a human-readable description of the status of this operation. Maximal length of the note is 1kB, but libraries should be prepared to handle values up to 64kB.")
    reason: Optional[StrictStr] = Field(default=None, description="reason is why the action was taken. It is human-readable. This field cannot be empty for new Events and it can have at most 128 characters.")
    regarding: Optional[V1ObjectReference] = None
    related: Optional[V1ObjectReference] = None
    reporting_controller: Optional[StrictStr] = Field(default=None, validation_alias=AliasChoices("reportingController", "reporting_controller"), serialization_alias="reportingController", description="reportingController is the name of the controller that emitted this Event, e.g. `kubernetes.io/kubelet`. This field cannot be empty for new Events.")
    reporting_instance: Optional[StrictStr] = Field(default=None, validation_alias=AliasChoices("reportingInstance", "reporting_instance"), serialization_alias="reportingInstance", description="reportingInstance is the ID of the controller instance, e.g. `kubelet-xyzf`. This field cannot be empty for new Events and it can have at most 128 characters.")
    series: Optional[EventsV1EventSeries] = None
    type: Optional[StrictStr] = Field(default=None, description="type is the type of this event (Normal, Warning), new types could be added in the future. It is machine-readable. This field cannot be empty for new Events.")
    openapi_types: ClassVar[Dict[str, str]] = {
        "action": "str",
        "api_version": "str",
        "deprecated_count": "int",
        "deprecated_first_timestamp": "datetime",
        "deprecated_last_timestamp": "datetime",
        "deprecated_source": "V1EventSource",
        "event_time": "datetime",
        "kind": "str",
        "metadata": "V1ObjectMeta",
        "note": "str",
        "reason": "str",
        "regarding": "V1ObjectReference",
        "related": "V1ObjectReference",
        "reporting_controller": "str",
        "reporting_instance": "str",
        "series": "EventsV1EventSeries",
        "type": "str"
    }

    attribute_map: ClassVar[Dict[str, str]] = {
        "action": "action",
        "api_version": "apiVersion",
        "deprecated_count": "deprecatedCount",
        "deprecated_first_timestamp": "deprecatedFirstTimestamp",
        "deprecated_last_timestamp": "deprecatedLastTimestamp",
        "deprecated_source": "deprecatedSource",
        "event_time": "eventTime",
        "kind": "kind",
        "metadata": "metadata",
        "note": "note",
        "reason": "reason",
        "regarding": "regarding",
        "related": "related",
        "reporting_controller": "reportingController",
        "reporting_instance": "reportingInstance",
        "series": "series",
        "type": "type"
    }
    __properties: ClassVar[List[str]] = ["action", "apiVersion", "deprecatedCount", "deprecatedFirstTimestamp", "deprecatedLastTimestamp", "deprecatedSource", "eventTime", "kind", "metadata", "note", "reason", "regarding", "related", "reportingController", "reportingInstance", "series", "type"]

    @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 "apiVersion" not in obj and "api_version" in obj:
            obj["apiVersion"] = obj["api_version"]
        obj.pop("api_version", None)
        if "deprecatedCount" not in obj and "deprecated_count" in obj:
            obj["deprecatedCount"] = obj["deprecated_count"]
        obj.pop("deprecated_count", None)
        if "deprecatedFirstTimestamp" not in obj and "deprecated_first_timestamp" in obj:
            obj["deprecatedFirstTimestamp"] = obj["deprecated_first_timestamp"]
        obj.pop("deprecated_first_timestamp", None)
        if "deprecatedLastTimestamp" not in obj and "deprecated_last_timestamp" in obj:
            obj["deprecatedLastTimestamp"] = obj["deprecated_last_timestamp"]
        obj.pop("deprecated_last_timestamp", None)
        if "deprecatedSource" not in obj and "deprecated_source" in obj:
            obj["deprecatedSource"] = obj["deprecated_source"]
        obj.pop("deprecated_source", None)
        if "eventTime" not in obj and "event_time" in obj:
            obj["eventTime"] = obj["event_time"]
        obj.pop("event_time", None)
        if "reportingController" not in obj and "reporting_controller" in obj:
            obj["reportingController"] = obj["reporting_controller"]
        obj.pop("reporting_controller", None)
        if "reportingInstance" not in obj and "reporting_instance" in obj:
            obj["reportingInstance"] = obj["reporting_instance"]
        obj.pop("reporting_instance", 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, EventsV1Event):
            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, EventsV1Event):
            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 EventsV1Event 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 {
            ("action" if serialize else "action"): _to_legacy_value(getattr(self, "action", None), serialize),
            ("apiVersion" if serialize else "api_version"): _to_legacy_value(getattr(self, "api_version", None), serialize),
            ("deprecatedCount" if serialize else "deprecated_count"): _to_legacy_value(getattr(self, "deprecated_count", None), serialize),
            ("deprecatedFirstTimestamp" if serialize else "deprecated_first_timestamp"): _to_legacy_value(getattr(self, "deprecated_first_timestamp", None), serialize),
            ("deprecatedLastTimestamp" if serialize else "deprecated_last_timestamp"): _to_legacy_value(getattr(self, "deprecated_last_timestamp", None), serialize),
            ("deprecatedSource" if serialize else "deprecated_source"): _to_legacy_value(getattr(self, "deprecated_source", None), serialize),
            ("eventTime" if serialize else "event_time"): _to_legacy_value(getattr(self, "event_time", None), serialize),
            ("kind" if serialize else "kind"): _to_legacy_value(getattr(self, "kind", None), serialize),
            ("metadata" if serialize else "metadata"): _to_legacy_value(getattr(self, "metadata", None), serialize),
            ("note" if serialize else "note"): _to_legacy_value(getattr(self, "note", None), serialize),
            ("reason" if serialize else "reason"): _to_legacy_value(getattr(self, "reason", None), serialize),
            ("regarding" if serialize else "regarding"): _to_legacy_value(getattr(self, "regarding", None), serialize),
            ("related" if serialize else "related"): _to_legacy_value(getattr(self, "related", None), serialize),
            ("reportingController" if serialize else "reporting_controller"): _to_legacy_value(getattr(self, "reporting_controller", None), serialize),
            ("reportingInstance" if serialize else "reporting_instance"): _to_legacy_value(getattr(self, "reporting_instance", None), serialize),
            ("series" if serialize else "series"): _to_legacy_value(getattr(self, "series", None), serialize),
            ("type" if serialize else "type"): _to_legacy_value(getattr(self, "type", 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 deprecated_source
        if self.deprecated_source:
            _dict['deprecatedSource'] = _to_openapi_value(self.deprecated_source)
        # override the default output from pydantic by calling `to_dict()` of metadata
        if self.metadata:
            _dict['metadata'] = _to_openapi_value(self.metadata)
        # override the default output from pydantic by calling `to_dict()` of regarding
        if self.regarding:
            _dict['regarding'] = _to_openapi_value(self.regarding)
        # override the default output from pydantic by calling `to_dict()` of related
        if self.related:
            _dict['related'] = _to_openapi_value(self.related)
        # override the default output from pydantic by calling `to_dict()` of series
        if self.series:
            _dict['series'] = _to_openapi_value(self.series)
        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 EventsV1Event 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({
            "action": obj.get("action"),
            "apiVersion": obj.get("apiVersion"),
            "deprecatedCount": obj.get("deprecatedCount"),
            "deprecatedFirstTimestamp": obj.get("deprecatedFirstTimestamp"),
            "deprecatedLastTimestamp": obj.get("deprecatedLastTimestamp"),
            "deprecatedSource": V1EventSource.from_dict(obj["deprecatedSource"]) if obj.get("deprecatedSource") is not None else None,
            "eventTime": obj.get("eventTime"),
            "kind": obj.get("kind"),
            "metadata": V1ObjectMeta.from_dict(obj["metadata"]) if obj.get("metadata") is not None else None,
            "note": obj.get("note"),
            "reason": obj.get("reason"),
            "regarding": V1ObjectReference.from_dict(obj["regarding"]) if obj.get("regarding") is not None else None,
            "related": V1ObjectReference.from_dict(obj["related"]) if obj.get("related") is not None else None,
            "reportingController": obj.get("reportingController"),
            "reportingInstance": obj.get("reportingInstance"),
            "series": EventsV1EventSeries.from_dict(obj["series"]) if obj.get("series") is not None else None,
            "type": obj.get("type")
        })
        return _obj
