# 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, StrictStr, field_validator
from typing import Any, ClassVar, Dict, List, Optional
from typing_extensions import Annotated
from instana_client.models.http_endpoint_rule import HttpEndpointRule
from typing import Optional, Set
from typing_extensions import Self

class EndpointConfig(BaseModel):
    """
    EndpointConfig
    """ # noqa: E501
    endpoint_case: StrictStr = Field(description="This represents case sensitivity of endpoints of a service. Let's say in a service there are three endpoints, `user`, `Order` and `PAYMENT`:   For example, if `endpointCase` is `UPPER`, then endpoint names are converted to `USER`, `ORDER` and `PAYMENT`.   If `endpointCase` is `LOWER`, then endpoint names are converted to `user`, `order` and `payment`.   If `endpointCase` is `ORIGINAL`, then endpoint names are converted to `user`, `Order` and `PAYMENT`. ", alias="endpointCase")
    endpoint_name_by_collected_path_template_rule_enabled: Optional[StrictBool] = Field(default=None, description="The highest default precedence of endpoint rule is creating endpoint is based on path template. For example, ``` /hospital/1948/patient/291148 /hospital/728/patient/924892 /hospital/47/patient/25978 /hospital/108429/patient/1847 ``` can be considered as `/hospital/{hid}/patient/{pid}` if this rule is enabled. For most of the use cases, this rule should be enabled. ", alias="endpointNameByCollectedPathTemplateRuleEnabled")
    endpoint_name_by_first_path_segment_rule_enabled: Optional[StrictBool] = Field(default=None, description="There are endpoint extraction rules in Instana which take the first path segment from the HTTP request and turn this into an endpoint name. For example, given the following URLs `/users/123/profile` and `/users/123/settings`, the extraction rule will only take the first segment. As a result endpoint name will be `users`. Although this is useful in cases where broad overview of monitoring is required, lot of use cases are more specified. Considering the above example, if this rule is enabled, Instana can't distinguish between `profile` or `settings` as endpoints. For use cases where endpoints has to be monitored at fine granular level, this flag should be set to `false`. ", alias="endpointNameByFirstPathSegmentRuleEnabled")
    rules: Optional[Annotated[List[HttpEndpointRule], Field(min_length=1, max_length=500)]] = Field(default=None, description="Specify custom rule configuration apart from Instana predefined rules. This rule has the highest precedence. This is only available for HTTP endpoints.")
    service_id: StrictStr = Field(description="An Instana generated unique identifier for a Service. If specified, the list of results will be filtered for the specified Service ID. Eg: `3feb3dcd206c166ef2b41c707e0cd38d7cd325aa`. One can see the service id from Instana UI by going to a Service page. In the URL, there will be `serviceId=3feb3dcd206c166ef2b41c707e0cd38d7cd325aa`. Alternatively, one can use `Get services` API endpoint to get the service id in `id` parameter. ", alias="serviceId")
    __properties: ClassVar[List[str]] = ["endpointCase", "endpointNameByCollectedPathTemplateRuleEnabled", "endpointNameByFirstPathSegmentRuleEnabled", "rules", "serviceId"]

    @field_validator('endpoint_case')
    def endpoint_case_validate_enum(cls, value):
        """Validates the enum"""
        if value not in set(['ORIGINAL', 'LOWER', 'UPPER']):
            raise ValueError("must be one of enum values ('ORIGINAL', 'LOWER', 'UPPER')")
        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 EndpointConfig 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 rules (list)
        _items = []
        if self.rules:
            for _item_rules in self.rules:
                if _item_rules:
                    _items.append(_item_rules.to_dict())
            _dict['rules'] = _items
        return _dict

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

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

        _obj = cls.model_validate({
            "endpointCase": obj.get("endpointCase"),
            "endpointNameByCollectedPathTemplateRuleEnabled": obj.get("endpointNameByCollectedPathTemplateRuleEnabled"),
            "endpointNameByFirstPathSegmentRuleEnabled": obj.get("endpointNameByFirstPathSegmentRuleEnabled"),
            "rules": [HttpEndpointRule.from_dict(_item) for _item in obj["rules"]] if obj.get("rules") is not None else None,
            "serviceId": obj.get("serviceId")
        })
        return _obj


