# coding: utf-8

"""
    STACKIT DNS API

    This api provides dns

    The version of the OpenAPI document: 1.0
    Contact: dns@stackit.cloud
    Generated by OpenAPI Generator (https://openapi-generator.tech)

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

from __future__ import annotations

import json
import pprint
from typing import Any, ClassVar, Dict, List, Optional, Set

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

from stackit.dns.models.record import Record


class RecordSet(BaseModel):
    """
    RRSet.
    """  # noqa: E501

    active: Optional[StrictBool] = Field(default=None, description="if the record set is active or not")
    comment: Optional[Annotated[str, Field(strict=True, max_length=255)]] = Field(default=None, description="comment")
    creation_finished: StrictStr = Field(description="when record set creation finished", alias="creationFinished")
    creation_started: StrictStr = Field(description="when record set creation started", alias="creationStarted")
    error: Optional[Annotated[str, Field(strict=True, max_length=2000)]] = Field(
        default=None, description="Error shows error in case create/update/delete failed"
    )
    id: StrictStr = Field(description="rr set id")
    name: Annotated[str, Field(min_length=1, strict=True, max_length=253)] = Field(
        description="name of the record which should be a valid domain according to rfc1035 Section 2.3.4. For APEX records (same as zone name), the zone name itself has to be put in here."
    )
    records: Annotated[List[Record], Field(min_length=1)] = Field(description="records")
    state: StrictStr = Field(description="record set state")
    ttl: Annotated[int, Field(le=99999999, strict=True, ge=60)] = Field(description="time to live")
    type: StrictStr = Field(description="record set type")
    update_finished: StrictStr = Field(description="when record set update/deletion finished", alias="updateFinished")
    update_started: StrictStr = Field(description="when record set update/deletion started", alias="updateStarted")
    __properties: ClassVar[List[str]] = [
        "active",
        "comment",
        "creationFinished",
        "creationStarted",
        "error",
        "id",
        "name",
        "records",
        "state",
        "ttl",
        "type",
        "updateFinished",
        "updateStarted",
    ]

    @field_validator("state")
    def state_validate_enum(cls, value):
        """Validates the enum"""
        if value not in set(
            [
                "CREATING",
                "CREATE_SUCCEEDED",
                "CREATE_FAILED",
                "DELETING",
                "DELETE_SUCCEEDED",
                "DELETE_FAILED",
                "UPDATING",
                "UPDATE_SUCCEEDED",
                "UPDATE_FAILED",
            ]
        ):
            raise ValueError(
                "must be one of enum values ('CREATING', 'CREATE_SUCCEEDED', 'CREATE_FAILED', 'DELETING', 'DELETE_SUCCEEDED', 'DELETE_FAILED', 'UPDATING', 'UPDATE_SUCCEEDED', 'UPDATE_FAILED')"
            )
        return value

    @field_validator("type")
    def type_validate_enum(cls, value):
        """Validates the enum"""
        if value not in set(
            [
                "A",
                "AAAA",
                "SOA",
                "CNAME",
                "NS",
                "MX",
                "TXT",
                "SRV",
                "PTR",
                "ALIAS",
                "DNAME",
                "CAA",
                "DNSKEY",
                "DS",
                "LOC",
                "NAPTR",
                "SSHFP",
                "TLSA",
                "URI",
                "CERT",
                "SVCB",
                "TYPE",
                "CSYNC",
                "HINFO",
                "HTTPS",
            ]
        ):
            raise ValueError(
                "must be one of enum values ('A', 'AAAA', 'SOA', 'CNAME', 'NS', 'MX', 'TXT', 'SRV', 'PTR', 'ALIAS', 'DNAME', 'CAA', 'DNSKEY', 'DS', 'LOC', 'NAPTR', 'SSHFP', 'TLSA', 'URI', 'CERT', 'SVCB', 'TYPE', 'CSYNC', 'HINFO', 'HTTPS')"
            )
        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 RecordSet 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 records (list)
        _items = []
        if self.records:
            for _item_records in self.records:
                if _item_records:
                    _items.append(_item_records.to_dict())
            _dict["records"] = _items
        return _dict

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

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

        _obj = cls.model_validate(
            {
                "active": obj.get("active"),
                "comment": obj.get("comment"),
                "creationFinished": obj.get("creationFinished"),
                "creationStarted": obj.get("creationStarted"),
                "error": obj.get("error"),
                "id": obj.get("id"),
                "name": obj.get("name"),
                "records": (
                    [Record.from_dict(_item) for _item in obj["records"]] if obj.get("records") is not None else None
                ),
                "state": obj.get("state"),
                "ttl": obj.get("ttl"),
                "type": obj.get("type"),
                "updateFinished": obj.get("updateFinished"),
                "updateStarted": obj.get("updateStarted"),
            }
        )
        return _obj
