# 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.client.models.core_v1_event_series import CoreV1EventSeries
from kubernetes.client.models.v1_event_source import V1EventSource
from kubernetes.client.models.v1_object_meta import V1ObjectMeta
from kubernetes.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 CoreV1Event(BaseModel):
    """
    Event is a report of an event somewhere in the cluster.  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="What action was taken/failed regarding to the Regarding object.")
    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")
    count: Optional[StrictInt] = Field(default=None, description="The number of times this event has occurred.")
    event_time: Optional[datetime] = Field(default=None, validation_alias=AliasChoices("eventTime", "event_time"), serialization_alias="eventTime", description="Time when this Event was first observed.")
    first_timestamp: Optional[datetime] = Field(default=None, validation_alias=AliasChoices("firstTimestamp", "first_timestamp"), serialization_alias="firstTimestamp", description="The time at which the event was first recorded. (Time of server receipt is in TypeMeta.)")
    involved_object: V1ObjectReference = Field(validation_alias=AliasChoices("involvedObject", "involved_object"), serialization_alias="involvedObject")
    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")
    last_timestamp: Optional[datetime] = Field(default=None, validation_alias=AliasChoices("lastTimestamp", "last_timestamp"), serialization_alias="lastTimestamp", description="The time at which the most recent occurrence of this event was recorded.")
    message: Optional[StrictStr] = Field(default=None, description="A human-readable description of the status of this operation.")
    metadata: V1ObjectMeta
    reason: Optional[StrictStr] = Field(default=None, description="This should be a short, machine understandable string that gives the reason for the transition into the object's current status.")
    related: Optional[V1ObjectReference] = None
    reporting_component: Optional[StrictStr] = Field(default=None, validation_alias=AliasChoices("reportingComponent", "reporting_component"), serialization_alias="reportingComponent", description="Name of the controller that emitted this Event, e.g. `kubernetes.io/kubelet`.")
    reporting_instance: Optional[StrictStr] = Field(default=None, validation_alias=AliasChoices("reportingInstance", "reporting_instance"), serialization_alias="reportingInstance", description="ID of the controller instance, e.g. `kubelet-xyzf`.")
    series: Optional[CoreV1EventSeries] = None
    source: Optional[V1EventSource] = None
    type: Optional[StrictStr] = Field(default=None, description="Type of this event (Normal, Warning), new types could be added in the future")
    openapi_types: ClassVar[Dict[str, str]] = {
        "action": "str",
        "api_version": "str",
        "count": "int",
        "event_time": "datetime",
        "first_timestamp": "datetime",
        "involved_object": "V1ObjectReference",
        "kind": "str",
        "last_timestamp": "datetime",
        "message": "str",
        "metadata": "V1ObjectMeta",
        "reason": "str",
        "related": "V1ObjectReference",
        "reporting_component": "str",
        "reporting_instance": "str",
        "series": "CoreV1EventSeries",
        "source": "V1EventSource",
        "type": "str"
    }

    attribute_map: ClassVar[Dict[str, str]] = {
        "action": "action",
        "api_version": "apiVersion",
        "count": "count",
        "event_time": "eventTime",
        "first_timestamp": "firstTimestamp",
        "involved_object": "involvedObject",
        "kind": "kind",
        "last_timestamp": "lastTimestamp",
        "message": "message",
        "metadata": "metadata",
        "reason": "reason",
        "related": "related",
        "reporting_component": "reportingComponent",
        "reporting_instance": "reportingInstance",
        "series": "series",
        "source": "source",
        "type": "type"
    }
    __properties: ClassVar[List[str]] = ["action", "apiVersion", "count", "eventTime", "firstTimestamp", "involvedObject", "kind", "lastTimestamp", "message", "metadata", "reason", "related", "reportingComponent", "reportingInstance", "series", "source", "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 "eventTime" not in obj and "event_time" in obj:
            obj["eventTime"] = obj["event_time"]
        obj.pop("event_time", None)
        if "firstTimestamp" not in obj and "first_timestamp" in obj:
            obj["firstTimestamp"] = obj["first_timestamp"]
        obj.pop("first_timestamp", None)
        if "involvedObject" not in obj and "involved_object" in obj:
            obj["involvedObject"] = obj["involved_object"]
        obj.pop("involved_object", None)
        if "lastTimestamp" not in obj and "last_timestamp" in obj:
            obj["lastTimestamp"] = obj["last_timestamp"]
        obj.pop("last_timestamp", None)
        if "reportingComponent" not in obj and "reporting_component" in obj:
            obj["reportingComponent"] = obj["reporting_component"]
        obj.pop("reporting_component", 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, CoreV1Event):
            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, CoreV1Event):
            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 CoreV1Event 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),
            ("count" if serialize else "count"): _to_legacy_value(getattr(self, "count", None), serialize),
            ("eventTime" if serialize else "event_time"): _to_legacy_value(getattr(self, "event_time", None), serialize),
            ("firstTimestamp" if serialize else "first_timestamp"): _to_legacy_value(getattr(self, "first_timestamp", None), serialize),
            ("involvedObject" if serialize else "involved_object"): _to_legacy_value(getattr(self, "involved_object", None), serialize),
            ("kind" if serialize else "kind"): _to_legacy_value(getattr(self, "kind", None), serialize),
            ("lastTimestamp" if serialize else "last_timestamp"): _to_legacy_value(getattr(self, "last_timestamp", None), serialize),
            ("message" if serialize else "message"): _to_legacy_value(getattr(self, "message", None), serialize),
            ("metadata" if serialize else "metadata"): _to_legacy_value(getattr(self, "metadata", None), serialize),
            ("reason" if serialize else "reason"): _to_legacy_value(getattr(self, "reason", None), serialize),
            ("related" if serialize else "related"): _to_legacy_value(getattr(self, "related", None), serialize),
            ("reportingComponent" if serialize else "reporting_component"): _to_legacy_value(getattr(self, "reporting_component", 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),
            ("source" if serialize else "source"): _to_legacy_value(getattr(self, "source", 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 involved_object
        if self.involved_object:
            _dict['involvedObject'] = _to_openapi_value(self.involved_object)
        # 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 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)
        # override the default output from pydantic by calling `to_dict()` of source
        if self.source:
            _dict['source'] = _to_openapi_value(self.source)
        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 CoreV1Event 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"),
            "count": obj.get("count"),
            "eventTime": obj.get("eventTime"),
            "firstTimestamp": obj.get("firstTimestamp"),
            "involvedObject": V1ObjectReference.from_dict(obj["involvedObject"]) if obj.get("involvedObject") is not None else None,
            "kind": obj.get("kind"),
            "lastTimestamp": obj.get("lastTimestamp"),
            "message": obj.get("message"),
            "metadata": V1ObjectMeta.from_dict(obj["metadata"]) if obj.get("metadata") is not None else None,
            "reason": obj.get("reason"),
            "related": V1ObjectReference.from_dict(obj["related"]) if obj.get("related") is not None else None,
            "reportingComponent": obj.get("reportingComponent"),
            "reportingInstance": obj.get("reportingInstance"),
            "series": CoreV1EventSeries.from_dict(obj["series"]) if obj.get("series") is not None else None,
            "source": V1EventSource.from_dict(obj["source"]) if obj.get("source") is not None else None,
            "type": obj.get("type")
        })
        return _obj
