# The Okta software accompanied by this notice is provided pursuant to the following terms:
# Copyright © 2025-Present, Okta, Inc.
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the
# License.
# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.
# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS
# IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and limitations under the License.
# coding: utf-8

"""
Okta Admin Management

Allows customers to easily access the Okta Management APIs

The version of the OpenAPI document: 5.1.0
Contact: devex-public@okta.com
Generated by OpenAPI Generator (https://openapi-generator.tech)

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

from __future__ import annotations

import json
import pprint
import re  # noqa: F401
from datetime import datetime
from typing import Any, ClassVar, Dict, List
from typing import Optional, Set

from pydantic import (
    BaseModel,
    ConfigDict,
    Field,
    StrictBool,
    StrictStr,
    field_validator,
)
from typing_extensions import Self

from okta.models.network_zone_address import NetworkZoneAddress
from okta.models.network_zone_links import NetworkZoneLinks
from okta.models.network_zone_location import NetworkZoneLocation
from okta.models.network_zone_status import NetworkZoneStatus
from okta.models.network_zone_type import NetworkZoneType
from okta.models.network_zone_usage import NetworkZoneUsage


class NetworkZone(BaseModel):
    """
    NetworkZone
    """  # noqa: E501

    asns: Optional[List[StrictStr]] = Field(
        default=None,
        description="Dynamic network zone property. array of strings that represent an "
                    "ASN numeric value",
    )
    created: Optional[datetime] = Field(
        default=None, description="Timestamp when the network zone was created"
    )
    gateways: Optional[List[NetworkZoneAddress]] = Field(
        default=None,
        description="IP network zone property: the IP addresses (range or "
                    "CIDR form) of this zone. The maximum array length is 150 entries for admin-created IP zones, "
                    "1000 entries for IP blocklist zones, and 5000 entries for the default system IP Zone.",
    )
    id: Optional[StrictStr] = Field(
        default=None, description="Unique identifier for the network zone"
    )
    last_updated: Optional[datetime] = Field(
        default=None,
        description="Timestamp when the network zone was last modified",
        alias="lastUpdated",
    )
    locations: Optional[List[NetworkZoneLocation]] = Field(
        default=None,
        description="Dynamic network zone property: an array of geolocations of this network zone",
    )
    name: Optional[StrictStr] = Field(
        default=None,
        description="Unique name for this network zone. Maximum of 128 characters.",
    )
    proxies: Optional[List[NetworkZoneAddress]] = Field(
        default=None,
        description="IP network zone property: the IP addresses (range or CIDR form) that are allowed to forward a request "
                    "from gateway addresses These proxies are automatically trusted by Threat Insights, and used to "
                    "identify the client IP of a request. The maximum array length is 150 entries for admin-created zones "
                    "and 5000 entries for the default system IP Zone.",
    )
    proxy_type: Optional[StrictStr] = Field(
        default=None,
        description="Dynamic network zone property: the proxy type used",
        alias="proxyType",
    )
    status: Optional[NetworkZoneStatus] = None
    system: Optional[StrictBool] = Field(
        default=None,
        description="Indicates if this is a system network zone. For admin-created zones, this is always `false`. The "
                    "system IP Policy Network Zone (`LegacyIpZone`) is included by default in your Okta org. Notice that "
                    "`system=true` for the `LegacyIpZone` object. Admin users can modify the name of this default system "
                    "Zone and can add up to 5000 gateway or proxy IP entries.",
    )
    type: Optional[NetworkZoneType] = None
    usage: Optional[NetworkZoneUsage] = None
    links: Optional[NetworkZoneLinks] = Field(default=None, alias="_links")
    __properties: ClassVar[List[str]] = [
        "asns",
        "created",
        "gateways",
        "id",
        "lastUpdated",
        "locations",
        "name",
        "proxies",
        "proxyType",
        "status",
        "system",
        "type",
        "usage",
        "_links",
    ]

    @field_validator("proxy_type")
    def proxy_type_validate_enum(cls, value):
        """Validates the enum"""
        if value is None:
            return value

        if value not in set(["null", "Any", "Tor", "NotTorAnonymizer"]):
            raise ValueError(
                "must be one of enum values ('null', 'Any', 'Tor', 'NotTorAnonymizer')"
            )
        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 NetworkZone 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.
        * OpenAPI `readOnly` fields are excluded.
        * OpenAPI `readOnly` fields are excluded.
        * OpenAPI `readOnly` fields are excluded.
        """
        excluded_fields: Set[str] = set(
            [
                "created",
                "id",
                "last_updated",
            ]
        )

        _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 gateways (list)
        _items = []
        if self.gateways:
            for _item in self.gateways:
                if _item:
                    _items.append(_item.to_dict())
            _dict["gateways"] = _items
        # override the default output from pydantic by calling `to_dict()` of each item in locations (list)
        _items = []
        if self.locations:
            for _item in self.locations:
                if _item:
                    _items.append(_item.to_dict())
            _dict["locations"] = _items
        # override the default output from pydantic by calling `to_dict()` of each item in proxies (list)
        _items = []
        if self.proxies:
            for _item in self.proxies:
                if _item:
                    _items.append(_item.to_dict())
            _dict["proxies"] = _items
        # override the default output from pydantic by calling `to_dict()` of links
        if self.links:
            if not isinstance(self.links, dict):
                _dict["_links"] = self.links.to_dict()
            else:
                _dict["_links"] = self.links

        # set to None if proxies (nullable) is None
        # and model_fields_set contains the field
        if self.proxies is None and "proxies" in self.model_fields_set:
            _dict["proxies"] = None

        return _dict

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

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

        _obj = cls.model_validate(
            {
                "asns": obj.get("asns"),
                "created": obj.get("created"),
                "gateways": (
                    [NetworkZoneAddress.from_dict(_item) for _item in obj["gateways"]]
                    if obj.get("gateways") is not None
                    else None
                ),
                "id": obj.get("id"),
                "lastUpdated": obj.get("lastUpdated"),
                "locations": (
                    [NetworkZoneLocation.from_dict(_item) for _item in obj["locations"]]
                    if obj.get("locations") is not None
                    else None
                ),
                "name": obj.get("name"),
                "proxies": (
                    [NetworkZoneAddress.from_dict(_item) for _item in obj["proxies"]]
                    if obj.get("proxies") is not None
                    else None
                ),
                "proxyType": obj.get("proxyType"),
                "status": obj.get("status"),
                "system": obj.get("system"),
                "type": obj.get("type"),
                "usage": obj.get("usage"),
                "_links": (
                    NetworkZoneLinks.from_dict(obj["_links"])
                    if obj.get("_links") is not None
                    else None
                ),
            }
        )
        return _obj
