# coding: utf-8

"""
    Kubeflow Spark Operator OpenAPI Spec

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

    The version of the OpenAPI document: unversioned
    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 pydantic import BaseModel, ConfigDict, Field, StrictStr, field_validator
from typing import Any, ClassVar, Dict, List, Optional
from kubeflow_spark_api.models.io_k8s_api_networking_v1_network_policy_egress_rule import IoK8sApiNetworkingV1NetworkPolicyEgressRule
from kubeflow_spark_api.models.io_k8s_api_networking_v1_network_policy_ingress_rule import IoK8sApiNetworkingV1NetworkPolicyIngressRule
from kubeflow_spark_api.models.io_k8s_apimachinery_pkg_apis_meta_v1_label_selector import IoK8sApimachineryPkgApisMetaV1LabelSelector
from typing import Optional, Set
from typing_extensions import Self

class IoK8sApiNetworkingV1NetworkPolicySpec(BaseModel):
    """
    NetworkPolicySpec provides the specification of a NetworkPolicy
    """ # noqa: E501
    egress: Optional[List[IoK8sApiNetworkingV1NetworkPolicyEgressRule]] = Field(default=None, description="egress is a list of egress rules to be applied to the selected pods. Outgoing traffic is allowed if there are no NetworkPolicies selecting the pod (and cluster policy otherwise allows the traffic), OR if the traffic matches at least one egress rule across all of the NetworkPolicy objects whose podSelector matches the pod. If this field is empty then this NetworkPolicy limits all outgoing traffic (and serves solely to ensure that the pods it selects are isolated by default). This field is beta-level in 1.8")
    ingress: Optional[List[IoK8sApiNetworkingV1NetworkPolicyIngressRule]] = Field(default=None, description="ingress is a list of ingress rules to be applied to the selected pods. Traffic is allowed to a pod if there are no NetworkPolicies selecting the pod (and cluster policy otherwise allows the traffic), OR if the traffic source is the pod's local node, OR if the traffic matches at least one ingress rule across all of the NetworkPolicy objects whose podSelector matches the pod. If this field is empty then this NetworkPolicy does not allow any traffic (and serves solely to ensure that the pods it selects are isolated by default)")
    pod_selector: IoK8sApimachineryPkgApisMetaV1LabelSelector = Field(description="podSelector selects the pods to which this NetworkPolicy object applies. The array of ingress rules is applied to any pods selected by this field. Multiple network policies can select the same set of pods. In this case, the ingress rules for each are combined additively. This field is NOT optional and follows standard label selector semantics. An empty podSelector matches all pods in this namespace.", alias="podSelector")
    policy_types: Optional[List[StrictStr]] = Field(default=None, description="policyTypes is a list of rule types that the NetworkPolicy relates to. Valid options are [\"Ingress\"], [\"Egress\"], or [\"Ingress\", \"Egress\"]. If this field is not specified, it will default based on the existence of ingress or egress rules; policies that contain an egress section are assumed to affect egress, and all policies (whether or not they contain an ingress section) are assumed to affect ingress. If you want to write an egress-only policy, you must explicitly specify policyTypes [ \"Egress\" ]. Likewise, if you want to write a policy that specifies that no egress is allowed, you must specify a policyTypes value that include \"Egress\" (since such a policy would not include an egress section and would otherwise default to just [ \"Ingress\" ]). This field is beta-level in 1.8", alias="policyTypes")
    __properties: ClassVar[List[str]] = ["egress", "ingress", "podSelector", "policyTypes"]

    @field_validator('policy_types')
    def policy_types_validate_enum(cls, value):
        """Validates the enum"""
        if value is None:
            return value

        for i in value:
            if i not in set(['Egress', 'Ingress']):
                raise ValueError("each list item must be one of ('Egress', 'Ingress')")
        return value

    model_config = ConfigDict(
        populate_by_name=True,
        validate_assignment=True,
        protected_namespaces=(),
    )


    def to_str(self) -> str:
        """Returns the string representation of the model using alias"""
        return pprint.pformat(self.model_dump(by_alias=True))

    def to_json(self) -> str:
        """Returns the JSON representation of the model using alias"""
        # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
        return json.dumps(self.to_dict())

    @classmethod
    def from_json(cls, json_str: str) -> Optional[Self]:
        """Create an instance of IoK8sApiNetworkingV1NetworkPolicySpec from a JSON string"""
        return cls.from_dict(json.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.
        """
        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 egress (list)
        _items = []
        if self.egress:
            for _item_egress in self.egress:
                if _item_egress:
                    _items.append(_item_egress.to_dict())
            _dict['egress'] = _items
        # override the default output from pydantic by calling `to_dict()` of each item in ingress (list)
        _items = []
        if self.ingress:
            for _item_ingress in self.ingress:
                if _item_ingress:
                    _items.append(_item_ingress.to_dict())
            _dict['ingress'] = _items
        # override the default output from pydantic by calling `to_dict()` of pod_selector
        if self.pod_selector:
            _dict['podSelector'] = self.pod_selector.to_dict()
        return _dict

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

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

        _obj = cls.model_validate({
            "egress": [IoK8sApiNetworkingV1NetworkPolicyEgressRule.from_dict(_item) for _item in obj["egress"]] if obj.get("egress") is not None else None,
            "ingress": [IoK8sApiNetworkingV1NetworkPolicyIngressRule.from_dict(_item) for _item in obj["ingress"]] if obj.get("ingress") is not None else None,
            "podSelector": IoK8sApimachineryPkgApisMetaV1LabelSelector.from_dict(obj["podSelector"]) if obj.get("podSelector") is not None else None,
            "policyTypes": obj.get("policyTypes")
        })
        return _obj


