# coding: utf-8

"""
    STACKIT IaaS API

    This API allows you to create and modify IaaS resources.

    The version of the OpenAPI document: 2
    Contact: stackit-iaas@mail.schwarz
    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 typing import Any, ClassVar, Dict, List, Optional, Set

from pydantic import BaseModel, ConfigDict, Field, field_validator
from typing_extensions import Annotated, Self

from stackit.iaas.models.network_range import NetworkRange


class RegionalAreaIPv4(BaseModel):
    """
    The regional IPv4 config of a network area.
    """  # noqa: E501

    default_nameservers: Optional[Annotated[List[Annotated[str, Field(strict=True)]], Field(max_length=3)]] = Field(
        default=None, alias="defaultNameservers"
    )
    default_prefix_len: Annotated[int, Field(le=29, strict=True, ge=24)] = Field(
        description="The default prefix length for networks in the network area.", alias="defaultPrefixLen"
    )
    max_prefix_len: Annotated[int, Field(le=29, strict=True, ge=24)] = Field(
        description="The maximal prefix length for networks in the network area.", alias="maxPrefixLen"
    )
    min_prefix_len: Annotated[int, Field(le=29, strict=True, ge=8)] = Field(
        description="The minimal prefix length for networks in the network area.", alias="minPrefixLen"
    )
    network_ranges: Annotated[List[NetworkRange], Field(min_length=1, max_length=64)] = Field(
        description="A list of network ranges.", alias="networkRanges"
    )
    transfer_network: Annotated[str, Field(strict=True)] = Field(
        description="IPv4 Classless Inter-Domain Routing (CIDR).", alias="transferNetwork"
    )
    __properties: ClassVar[List[str]] = [
        "defaultNameservers",
        "defaultPrefixLen",
        "maxPrefixLen",
        "minPrefixLen",
        "networkRanges",
        "transferNetwork",
    ]

    @field_validator("transfer_network")
    def transfer_network_validate_regular_expression(cls, value):
        """Validates the regular expression"""
        if not re.match(
            r"^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\/(3[0-2]|2[0-9]|1[0-9]|[0-9]))$",
            value,
        ):
            raise ValueError(
                r"must validate the regular expression /^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\/(3[0-2]|2[0-9]|1[0-9]|[0-9]))$/"
            )
        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 RegionalAreaIPv4 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 network_ranges (list)
        _items = []
        if self.network_ranges:
            for _item_network_ranges in self.network_ranges:
                if _item_network_ranges:
                    _items.append(_item_network_ranges.to_dict())
            _dict["networkRanges"] = _items
        return _dict

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

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

        _obj = cls.model_validate(
            {
                "defaultNameservers": obj.get("defaultNameservers"),
                "defaultPrefixLen": obj.get("defaultPrefixLen") if obj.get("defaultPrefixLen") is not None else 25,
                "maxPrefixLen": obj.get("maxPrefixLen") if obj.get("maxPrefixLen") is not None else 29,
                "minPrefixLen": obj.get("minPrefixLen") if obj.get("minPrefixLen") is not None else 24,
                "networkRanges": (
                    [NetworkRange.from_dict(_item) for _item in obj["networkRanges"]]
                    if obj.get("networkRanges") is not None
                    else None
                ),
                "transferNetwork": obj.get("transferNetwork"),
            }
        )
        return _obj
