# 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
from typing import Any, ClassVar, Dict, List, Optional
from typing_extensions import Annotated
from instana_client.models.custom_payload_field import CustomPayloadField
from instana_client.models.synthetic_alert_rule import SyntheticAlertRule
from instana_client.models.synthetic_time_threshold import SyntheticTimeThreshold
from instana_client.models.tag_filter_expression_element import TagFilterExpressionElement
from typing import Optional, Set
from typing_extensions import Self

class SyntheticAlertConfigWithMetadata(BaseModel):
    """
    SyntheticAlertConfigWithMetadata
    """ # noqa: E501
    alert_channel_ids: Annotated[List[StrictStr], Field(min_length=0, max_length=1024)] = Field(description="List of IDs of alert channels defined in Instana. Can be left empty.", alias="alertChannelIds")
    created: Optional[Annotated[int, Field(strict=True, ge=1)]] = Field(default=None, description="Unix timestamp representing the creation time of this revision.")
    custom_payload_fields: Annotated[List[CustomPayloadField], Field(min_length=0, max_length=20)] = Field(description="Custom payload fields to send additional information in the alert notifications. Can be left empty.", alias="customPayloadFields")
    description: Annotated[str, Field(min_length=0, strict=True, max_length=65536)] = Field(description="Description of the synthetic alert configuration. Used as a template for the description of alert/event notifications triggered by this Smart Alert configuration.")
    enabled: Optional[StrictBool] = Field(default=None, description="Flag to indicate whether or not the configuration is enabled.")
    grace_period: Optional[StrictInt] = Field(default=None, description="The duration for which an alert remains open after conditions are no longer violated, with the alert auto-closing once the grace period expires.", alias="gracePeriod")
    id: Annotated[str, Field(min_length=0, strict=True, max_length=64)] = Field(description="ID of this Synthetic Alert Config. ")
    initial_created: Optional[Annotated[int, Field(strict=True, ge=1)]] = Field(default=None, description="Unix timestamp representing the time of the initial revision.", alias="initialCreated")
    name: Annotated[str, Field(min_length=0, strict=True, max_length=256)] = Field(description="Name of the synthetic alert configuration. Used as a template for the title of alert/event notifications triggered by this Smart Alert configuration.")
    read_only: Optional[StrictBool] = Field(default=None, description="Flag to indicate whether or not the configuration is read-only. Read-only access restricts modification of the config.", alias="readOnly")
    rule: SyntheticAlertRule
    severity: Optional[Annotated[int, Field(le=10, strict=True, ge=5)]] = Field(default=None, description="The severity of the alert when triggered, which is either 5 (Warning), or 10 (Critical).")
    synthetic_test_ids: List[StrictStr] = Field(description="IDs of the synthetic tests that this Smart Alert configuration is applied to.", alias="syntheticTestIds")
    tag_filter_expression: TagFilterExpressionElement = Field(alias="tagFilterExpression")
    time_threshold: SyntheticTimeThreshold = Field(alias="timeThreshold")
    __properties: ClassVar[List[str]] = ["alertChannelIds", "created", "customPayloadFields", "description", "enabled", "gracePeriod", "id", "initialCreated", "name", "readOnly", "rule", "severity", "syntheticTestIds", "tagFilterExpression", "timeThreshold"]

    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 SyntheticAlertConfigWithMetadata 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 custom_payload_fields (list)
        _items = []
        if self.custom_payload_fields:
            for _item_custom_payload_fields in self.custom_payload_fields:
                if _item_custom_payload_fields:
                    _items.append(_item_custom_payload_fields.to_dict())
            _dict['customPayloadFields'] = _items
        # override the default output from pydantic by calling `to_dict()` of rule
        if self.rule:
            _dict['rule'] = self.rule.to_dict()
        # override the default output from pydantic by calling `to_dict()` of tag_filter_expression
        if self.tag_filter_expression:
            _dict['tagFilterExpression'] = self.tag_filter_expression.to_dict()
        # override the default output from pydantic by calling `to_dict()` of time_threshold
        if self.time_threshold:
            _dict['timeThreshold'] = self.time_threshold.to_dict()
        return _dict

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

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

        _obj = cls.model_validate({
            "alertChannelIds": obj.get("alertChannelIds"),
            "created": obj.get("created"),
            "customPayloadFields": [CustomPayloadField.from_dict(_item) for _item in obj["customPayloadFields"]] if obj.get("customPayloadFields") is not None else None,
            "description": obj.get("description"),
            "enabled": obj.get("enabled"),
            "gracePeriod": obj.get("gracePeriod"),
            "id": obj.get("id"),
            "initialCreated": obj.get("initialCreated"),
            "name": obj.get("name"),
            "readOnly": obj.get("readOnly"),
            "rule": SyntheticAlertRule.from_dict(obj["rule"]) if obj.get("rule") is not None else None,
            "severity": obj.get("severity"),
            "syntheticTestIds": obj.get("syntheticTestIds"),
            "tagFilterExpression": TagFilterExpressionElement.from_dict(obj["tagFilterExpression"]) if obj.get("tagFilterExpression") is not None else None,
            "timeThreshold": SyntheticTimeThreshold.from_dict(obj["timeThreshold"]) if obj.get("timeThreshold") is not None else None
        })
        return _obj


