# coding: utf-8

"""
    Kestra EE

    All API operations, except for Superadmin-only endpoints, require a tenant identifier in the HTTP path.<br/> Endpoints designated as Superadmin-only are not tenant-scoped.

    The version of the OpenAPI document: v1
    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 datetime import datetime
from pydantic import BaseModel, ConfigDict, Field, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from kestra_api_client.models.configuration_usage import ConfigurationUsage
from kestra_api_client.models.execution_usage import ExecutionUsage
from kestra_api_client.models.flow_usage import FlowUsage
from kestra_api_client.models.host_usage import HostUsage
from kestra_api_client.models.plugin_metric import PluginMetric
from kestra_api_client.models.plugin_usage import PluginUsage
from kestra_api_client.models.server_type import ServerType
from kestra_api_client.models.service_usage import ServiceUsage
from typing import Optional, Set
from typing_extensions import Self

class Usage(BaseModel):
    """
    Usage
    """ # noqa: E501
    uuid: StrictStr
    start_uuid: StrictStr = Field(alias="startUuid")
    instance_uuid: StrictStr = Field(alias="instanceUuid")
    server_type: ServerType = Field(alias="serverType")
    version: StrictStr
    zone_id: StrictStr = Field(alias="zoneId")
    uri: Optional[StrictStr] = None
    environments: Optional[List[StrictStr]] = None
    start_time: datetime = Field(alias="startTime")
    host: Optional[HostUsage] = None
    configurations: Optional[ConfigurationUsage] = None
    plugins: Optional[List[PluginUsage]] = None
    flows: Optional[FlowUsage] = None
    executions: Optional[ExecutionUsage] = None
    services: Optional[ServiceUsage] = None
    plugin_metrics: Optional[List[PluginMetric]] = Field(default=None, alias="pluginMetrics")
    additional_properties: Dict[str, Any] = {}
    __properties: ClassVar[List[str]] = ["uuid", "startUuid", "instanceUuid", "serverType", "version", "zoneId", "uri", "environments", "startTime", "host", "configurations", "plugins", "flows", "executions", "services", "pluginMetrics"]

    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 Usage 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.
        * Fields in `self.additional_properties` are added to the output dict.
        """
        excluded_fields: Set[str] = set([
            "additional_properties",
        ])

        _dict = self.model_dump(
            by_alias=True,
            exclude=excluded_fields,
            exclude_none=True,
        )
        # override the default output from pydantic by calling `to_dict()` of host
        if self.host:
            _dict['host'] = self.host.to_dict()
        # override the default output from pydantic by calling `to_dict()` of configurations
        if self.configurations:
            _dict['configurations'] = self.configurations.to_dict()
        # override the default output from pydantic by calling `to_dict()` of each item in plugins (list)
        _items = []
        if self.plugins:
            for _item_plugins in self.plugins:
                if _item_plugins:
                    _items.append(_item_plugins.to_dict())
            _dict['plugins'] = _items
        # override the default output from pydantic by calling `to_dict()` of flows
        if self.flows:
            _dict['flows'] = self.flows.to_dict()
        # override the default output from pydantic by calling `to_dict()` of executions
        if self.executions:
            _dict['executions'] = self.executions.to_dict()
        # override the default output from pydantic by calling `to_dict()` of services
        if self.services:
            _dict['services'] = self.services.to_dict()
        # override the default output from pydantic by calling `to_dict()` of each item in plugin_metrics (list)
        _items = []
        if self.plugin_metrics:
            for _item_plugin_metrics in self.plugin_metrics:
                if _item_plugin_metrics:
                    _items.append(_item_plugin_metrics.to_dict())
            _dict['pluginMetrics'] = _items
        # puts key-value pairs in additional_properties in the top level
        if self.additional_properties is not None:
            for _key, _value in self.additional_properties.items():
                _dict[_key] = _value

        # set to None if uri (nullable) is None
        # and model_fields_set contains the field
        if self.uri is None and "uri" in self.model_fields_set:
            _dict['uri'] = None

        # set to None if environments (nullable) is None
        # and model_fields_set contains the field
        if self.environments is None and "environments" in self.model_fields_set:
            _dict['environments'] = None

        # set to None if services (nullable) is None
        # and model_fields_set contains the field
        if self.services is None and "services" in self.model_fields_set:
            _dict['services'] = None

        # set to None if plugin_metrics (nullable) is None
        # and model_fields_set contains the field
        if self.plugin_metrics is None and "plugin_metrics" in self.model_fields_set:
            _dict['pluginMetrics'] = None

        return _dict

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

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

        _obj = cls.model_validate({
            "uuid": obj.get("uuid"),
            "startUuid": obj.get("startUuid"),
            "instanceUuid": obj.get("instanceUuid"),
            "serverType": obj.get("serverType"),
            "version": obj.get("version"),
            "zoneId": obj.get("zoneId"),
            "uri": obj.get("uri"),
            "environments": obj.get("environments"),
            "startTime": obj.get("startTime"),
            "host": HostUsage.from_dict(obj["host"]) if obj.get("host") is not None else None,
            "configurations": ConfigurationUsage.from_dict(obj["configurations"]) if obj.get("configurations") is not None else None,
            "plugins": [PluginUsage.from_dict(_item) for _item in obj["plugins"]] if obj.get("plugins") is not None else None,
            "flows": FlowUsage.from_dict(obj["flows"]) if obj.get("flows") is not None else None,
            "executions": ExecutionUsage.from_dict(obj["executions"]) if obj.get("executions") is not None else None,
            "services": ServiceUsage.from_dict(obj["services"]) if obj.get("services") is not None else None,
            "pluginMetrics": [PluginMetric.from_dict(_item) for _item in obj["pluginMetrics"]] if obj.get("pluginMetrics") is not None else None
        })
        # store additional fields in additional_properties
        for _key in obj.keys():
            if _key not in cls.__properties:
                _obj.additional_properties[_key] = obj.get(_key)

        return _obj


