# 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, StrictBool, StrictInt, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from kestrapy.models.breakpoint import Breakpoint
from kestrapy.models.execution_kind import ExecutionKind
from kestrapy.models.execution_metadata import ExecutionMetadata
from kestrapy.models.execution_trigger import ExecutionTrigger
from kestrapy.models.label import Label
from kestrapy.models.state import State
from kestrapy.models.task_fixture import TaskFixture
from kestrapy.models.task_run import TaskRun
from typing import Optional, Set
from typing_extensions import Self

class Execution(BaseModel):
    """
    Execution
    """ # noqa: E501
    labels: Optional[List[Label]] = None
    id: StrictStr
    namespace: StrictStr
    flow_id: StrictStr = Field(alias="flowId")
    flow_revision: StrictInt = Field(alias="flowRevision")
    task_run_list: Optional[List[TaskRun]] = Field(default=None, alias="taskRunList")
    inputs: Optional[Dict[str, Dict[str, Any]]] = None
    outputs: Optional[Dict[str, Dict[str, Any]]] = None
    variables: Optional[Dict[str, Dict[str, Any]]] = None
    state: State
    parent_id: Optional[StrictStr] = Field(default=None, alias="parentId")
    original_id: Optional[StrictStr] = Field(default=None, alias="originalId")
    trigger: Optional[ExecutionTrigger] = None
    deleted: StrictBool
    metadata: Optional[ExecutionMetadata] = None
    schedule_date: Optional[datetime] = Field(default=None, alias="scheduleDate")
    trace_parent: Optional[StrictStr] = Field(default=None, alias="traceParent")
    fixtures: Optional[List[TaskFixture]] = None
    kind: Optional[ExecutionKind] = None
    breakpoints: Optional[List[Breakpoint]] = None
    additional_properties: Dict[str, Any] = {}
    __properties: ClassVar[List[str]] = ["labels", "id", "namespace", "flowId", "flowRevision", "taskRunList", "inputs", "outputs", "variables", "state", "parentId", "originalId", "trigger", "deleted", "metadata", "scheduleDate", "traceParent", "fixtures", "kind", "breakpoints"]

    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 Execution 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 each item in labels (list)
        _items = []
        if self.labels:
            for _item_labels in self.labels:
                if _item_labels:
                    _items.append(_item_labels.to_dict())
            _dict['labels'] = _items
        # override the default output from pydantic by calling `to_dict()` of each item in task_run_list (list)
        _items = []
        if self.task_run_list:
            for _item_task_run_list in self.task_run_list:
                if _item_task_run_list:
                    _items.append(_item_task_run_list.to_dict())
            _dict['taskRunList'] = _items
        # override the default output from pydantic by calling `to_dict()` of state
        if self.state:
            _dict['state'] = self.state.to_dict()
        # override the default output from pydantic by calling `to_dict()` of trigger
        if self.trigger:
            _dict['trigger'] = self.trigger.to_dict()
        # override the default output from pydantic by calling `to_dict()` of metadata
        if self.metadata:
            _dict['metadata'] = self.metadata.to_dict()
        # override the default output from pydantic by calling `to_dict()` of each item in fixtures (list)
        _items = []
        if self.fixtures:
            for _item_fixtures in self.fixtures:
                if _item_fixtures:
                    _items.append(_item_fixtures.to_dict())
            _dict['fixtures'] = _items
        # override the default output from pydantic by calling `to_dict()` of each item in breakpoints (list)
        _items = []
        if self.breakpoints:
            for _item_breakpoints in self.breakpoints:
                if _item_breakpoints:
                    _items.append(_item_breakpoints.to_dict())
            _dict['breakpoints'] = _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 schedule_date (nullable) is None
        # and model_fields_set contains the field
        if self.schedule_date is None and "schedule_date" in self.model_fields_set:
            _dict['scheduleDate'] = None

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

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

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

        return _dict

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

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

        _obj = cls.model_validate({
            "labels": [Label.from_dict(_item) for _item in obj["labels"]] if obj.get("labels") is not None else None,
            "id": obj.get("id"),
            "namespace": obj.get("namespace"),
            "flowId": obj.get("flowId"),
            "flowRevision": obj.get("flowRevision"),
            "taskRunList": [TaskRun.from_dict(_item) for _item in obj["taskRunList"]] if obj.get("taskRunList") is not None else None,
            "inputs": obj.get("inputs"),
            "outputs": obj.get("outputs"),
            "variables": obj.get("variables"),
            "state": State.from_dict(obj["state"]) if obj.get("state") is not None else None,
            "parentId": obj.get("parentId"),
            "originalId": obj.get("originalId"),
            "trigger": ExecutionTrigger.from_dict(obj["trigger"]) if obj.get("trigger") is not None else None,
            "deleted": obj.get("deleted"),
            "metadata": ExecutionMetadata.from_dict(obj["metadata"]) if obj.get("metadata") is not None else None,
            "scheduleDate": obj.get("scheduleDate"),
            "traceParent": obj.get("traceParent"),
            "fixtures": [TaskFixture.from_dict(_item) for _item in obj["fixtures"]] if obj.get("fixtures") is not None else None,
            "kind": obj.get("kind"),
            "breakpoints": [Breakpoint.from_dict(_item) for _item in obj["breakpoints"]] if obj.get("breakpoints") 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


