# coding: utf-8

"""
    Instana REST API documentation

    Documentation for INSTANA REST API

    The version of the OpenAPI document: 1.309.1268
    Contact: support@instana.com
    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, field_validator
from typing import Any, ClassVar, Dict, List, Optional
from typing_extensions import Annotated
from instana_client.models.span_excerpt import SpanExcerpt
from instana_client.models.span_relation import SpanRelation
from typing import Optional, Set
from typing_extensions import Self

class TraceActivityTreeNodeDetails(BaseModel):
    """
    TraceActivityTreeNodeDetails
    """ # noqa: E501
    batch_self_time: Optional[StrictInt] = Field(default=None, description="Sum of all self times in a batch of calls. For example, if 5 calls are in a batch and its self times are : `[1,2,3,4,5]` in milliseconds, then the batch self time would be sum of the self times, in this case, it will be 15 milliseconds. ", alias="batchSelfTime")
    batch_size: Optional[Annotated[int, Field(strict=True, ge=0)]] = Field(default=None, description="Number of calls in a batch.", alias="batchSize")
    destination: Optional[SpanRelation] = None
    duration: Optional[Annotated[int, Field(strict=True, ge=0)]] = Field(default=None, description="The total time taken for the entire operation of a call, from the moment the request was initiated to when the response was received. The time measured is in milliseconds. This is also known as latency of a call.")
    error_count: Optional[Annotated[int, Field(strict=True, ge=0)]] = Field(default=None, description="Represents whether the call is erroneous or not. 0 is not erroneous and 1 is erroneous.", alias="errorCount")
    id: StrictStr = Field(description="The call ID. A unique identifier for an individual call. For example: `1bcad5c82338deaf`.")
    is_synthetic: Optional[StrictBool] = Field(default=None, alias="isSynthetic")
    label: Annotated[str, Field(min_length=0, strict=True, max_length=128)] = Field(description="Name of the call. For example: `GET /articles/:id`.")
    logs: List[SpanExcerpt] = Field(description="Information about the logs attached to the call, if available.")
    min_self_time: Optional[StrictInt] = Field(default=None, description="The smallest self time in the batch. May be null to indicate that `minSelfTime` is unknown when this node has only an exit span and no children. The time measured is in milliseconds.", alias="minSelfTime")
    network_time: Optional[StrictInt] = Field(default=None, description="The time difference between the Exit Span Time of the caller and the Entry Span Time of the call. This value is measured in milliseconds and may be null if network time is not applicable.", alias="networkTime")
    raw_span_load_error: Optional[StrictStr] = Field(default=None, description="Whether an error occurred loading raw spans from external storage.", alias="rawSpanLoadError")
    source: Optional[SpanRelation] = None
    spans: Annotated[List[SpanExcerpt], Field(min_length=1, max_length=2)] = Field(description="Information about the spans from which the call is composed.")
    start: Optional[Annotated[int, Field(strict=True, ge=1)]] = Field(default=None, description="The timestamp when the call or request was initiated. For example, Unix epoch time in milliseconds `1735532879870` is `Monday, 30 December 2024 04:27:59.870 GMT`")
    synthetic: Optional[StrictBool] = None
    __properties: ClassVar[List[str]] = ["batchSelfTime", "batchSize", "destination", "duration", "errorCount", "id", "isSynthetic", "label", "logs", "minSelfTime", "networkTime", "rawSpanLoadError", "source", "spans", "start", "synthetic"]

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

        if value not in set(['UNKNOWN_ERROR', 'NOT_FOUND', 'PERMISSION_DENIED', 'NO_ERROR']):
            raise ValueError("must be one of enum values ('UNKNOWN_ERROR', 'NOT_FOUND', 'PERMISSION_DENIED', 'NO_ERROR')")
        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 TraceActivityTreeNodeDetails 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 destination
        if self.destination:
            _dict['destination'] = self.destination.to_dict()
        # override the default output from pydantic by calling `to_dict()` of each item in logs (list)
        _items = []
        if self.logs:
            for _item_logs in self.logs:
                if _item_logs:
                    _items.append(_item_logs.to_dict())
            _dict['logs'] = _items
        # override the default output from pydantic by calling `to_dict()` of source
        if self.source:
            _dict['source'] = self.source.to_dict()
        # override the default output from pydantic by calling `to_dict()` of each item in spans (list)
        _items = []
        if self.spans:
            for _item_spans in self.spans:
                if _item_spans:
                    _items.append(_item_spans.to_dict())
            _dict['spans'] = _items
        return _dict

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

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

        _obj = cls.model_validate({
            "batchSelfTime": obj.get("batchSelfTime"),
            "batchSize": obj.get("batchSize"),
            "destination": SpanRelation.from_dict(obj["destination"]) if obj.get("destination") is not None else None,
            "duration": obj.get("duration"),
            "errorCount": obj.get("errorCount"),
            "id": obj.get("id"),
            "isSynthetic": obj.get("isSynthetic"),
            "label": obj.get("label"),
            "logs": [SpanExcerpt.from_dict(_item) for _item in obj["logs"]] if obj.get("logs") is not None else None,
            "minSelfTime": obj.get("minSelfTime"),
            "networkTime": obj.get("networkTime"),
            "rawSpanLoadError": obj.get("rawSpanLoadError"),
            "source": SpanRelation.from_dict(obj["source"]) if obj.get("source") is not None else None,
            "spans": [SpanExcerpt.from_dict(_item) for _item in obj["spans"]] if obj.get("spans") is not None else None,
            "start": obj.get("start"),
            "synthetic": obj.get("synthetic")
        })
        return _obj


