# coding: utf-8

"""
    Test Results API

    Get test result metrics for Network and Application Synthetics tests.

    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, StrictBool, StrictInt, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from thousandeyes_sdk.test_results.models.dns_measurement_protocol import DnsMeasurementProtocol
from thousandeyes_sdk.test_results.models.dns_opcode import DnsOpcode
from thousandeyes_sdk.test_results.models.dns_qr import DnsQr
from thousandeyes_sdk.test_results.models.dns_resource_record import DnsResourceRecord
from thousandeyes_sdk.test_results.models.dns_response_code import DnsResponseCode
from thousandeyes_sdk.test_results.models.dns_timing import DnsTiming
from typing import Optional, Set
from typing_extensions import Self

class DnsServerResponse(BaseModel):
    """
    A DNS response received while resolving the HTTP test target.
    """ # noqa: E501
    id: Optional[StrictInt] = Field(default=None, description="DNS message ID.")
    qr: Optional[DnsQr] = None
    opcode: Optional[DnsOpcode] = None
    authoritative_answer: Optional[StrictBool] = Field(default=None, description="DNS header AA flag.", alias="authoritativeAnswer")
    truncation: Optional[StrictBool] = Field(default=None, description="DNS header TC flag.")
    recursion_desired: Optional[StrictBool] = Field(default=None, description="DNS header RD flag.", alias="recursionDesired")
    recursion_available: Optional[StrictBool] = Field(default=None, description="DNS header RA flag.", alias="recursionAvailable")
    zero: Optional[StrictBool] = Field(default=None, description="DNS header Z flag. Reserved and expected to be false.")
    authentic_data: Optional[StrictBool] = Field(default=None, description="DNS header AD flag.", alias="authenticData")
    checking_disabled: Optional[StrictBool] = Field(default=None, description="DNS header CD flag.", alias="checkingDisabled")
    response_code: Optional[DnsResponseCode] = Field(default=None, alias="responseCode")
    question: Optional[List[DnsResourceRecord]] = Field(default=None, description="Records in the DNS question section.")
    answer: Optional[List[DnsResourceRecord]] = Field(default=None, description="Records in the DNS answer section.")
    dns_resolver: Optional[StrictStr] = Field(default=None, description="DNS resolver that returned this response.", alias="dnsResolver")
    timing: Optional[DnsTiming] = None
    protocol: Optional[DnsMeasurementProtocol] = None
    __properties: ClassVar[List[str]] = ["id", "qr", "opcode", "authoritativeAnswer", "truncation", "recursionDesired", "recursionAvailable", "zero", "authenticData", "checkingDisabled", "responseCode", "question", "answer", "dnsResolver", "timing", "protocol"]

    model_config = ConfigDict(
        populate_by_name=True,
        validate_assignment=True,
        protected_namespaces=(),
        extra="allow",
    )


    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 self.model_dump_json(by_alias=True, exclude_unset=True, exclude_none=True)

    @classmethod
    def from_json(cls, json_str: str) -> Optional[Self]:
        """Create an instance of DnsServerResponse 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.
        * OpenAPI `readOnly` fields are excluded.
        * OpenAPI `readOnly` fields are excluded.
        * OpenAPI `readOnly` fields are excluded.
        * OpenAPI `readOnly` fields are excluded.
        * OpenAPI `readOnly` fields are excluded.
        * OpenAPI `readOnly` fields are excluded.
        """
        excluded_fields: Set[str] = set([
            "id",
            "authoritative_answer",
            "truncation",
            "recursion_desired",
            "recursion_available",
            "zero",
            "authentic_data",
            "checking_disabled",
            "dns_resolver",
        ])

        _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 question (list)
        _items = []
        if self.question:
            for _item in self.question:
                if _item:
                    _items.append(_item.to_dict())
            _dict['question'] = _items
        # override the default output from pydantic by calling `to_dict()` of each item in answer (list)
        _items = []
        if self.answer:
            for _item in self.answer:
                if _item:
                    _items.append(_item.to_dict())
            _dict['answer'] = _items
        # override the default output from pydantic by calling `to_dict()` of timing
        if self.timing:
            _dict['timing'] = self.timing.to_dict()
        return _dict

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

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

        _obj = cls.model_validate({
            "id": obj.get("id"),
            "qr": obj.get("qr"),
            "opcode": obj.get("opcode"),
            "authoritativeAnswer": obj.get("authoritativeAnswer"),
            "truncation": obj.get("truncation"),
            "recursionDesired": obj.get("recursionDesired"),
            "recursionAvailable": obj.get("recursionAvailable"),
            "zero": obj.get("zero"),
            "authenticData": obj.get("authenticData"),
            "checkingDisabled": obj.get("checkingDisabled"),
            "responseCode": obj.get("responseCode"),
            "question": [DnsResourceRecord.from_dict(_item) for _item in obj["question"]] if obj.get("question") is not None else None,
            "answer": [DnsResourceRecord.from_dict(_item) for _item in obj["answer"]] if obj.get("answer") is not None else None,
            "dnsResolver": obj.get("dnsResolver"),
            "timing": DnsTiming.from_dict(obj["timing"]) if obj.get("timing") is not None else None,
            "protocol": obj.get("protocol")
        })
        return _obj


