# coding: utf-8

"""
    FINBOURNE Workflow API

    FINBOURNE Technology  # noqa: E501

    Contact: info@finbourne.com
    Generated by OpenAPI Generator (https://openapi-generator.tech)

    Do not edit the class manually.
"""


from __future__ import annotations
import pprint
import re  # noqa: F401
import json

from datetime import datetime
from typing import Any, Dict, List, Optional
from pydantic import BaseModel, Field, StrictBool, StrictStr, conlist, constr
from lusid_workflow.models.resource_id import ResourceId
from lusid_workflow.models.stack import Stack
from lusid_workflow.models.task_definition_version import TaskDefinitionVersion
from lusid_workflow.models.task_instance_field import TaskInstanceField
from lusid_workflow.models.task_summary import TaskSummary
from lusid_workflow.models.version_info import VersionInfo

class Task(BaseModel):
    """
    Defines a Task created based on a Task Definition  # noqa: E501
    """
    id: StrictStr = Field(..., description="The unique id for this Task")
    task_definition_id: ResourceId = Field(..., alias="taskDefinitionId")
    task_definition_version: TaskDefinitionVersion = Field(..., alias="taskDefinitionVersion")
    task_definition_display_name: constr(strict=True, min_length=1) = Field(..., alias="taskDefinitionDisplayName", description="The display name of the Task Definition used by this Task")
    state: constr(strict=True, min_length=1) = Field(..., description="Current State")
    ultimate_parent_task: TaskSummary = Field(..., alias="ultimateParentTask")
    parent_task: Optional[TaskSummary] = Field(None, alias="parentTask")
    child_tasks: Optional[conlist(TaskSummary)] = Field(None, alias="childTasks", description="This Task's child tasks")
    correlation_ids: Optional[conlist(StrictStr)] = Field(None, alias="correlationIds", description="User-provided ID used to link entities and tasks")
    version: Optional[VersionInfo] = None
    terminal_state: StrictBool = Field(..., alias="terminalState", description="True if no onward transitions are possible")
    as_at_last_transition: Optional[datetime] = Field(None, alias="asAtLastTransition", description="Last Transition timestamp")
    fields: Optional[conlist(TaskInstanceField)] = Field(None, description="Fields and their latest values - should correspond with the Task Definition field schema")
    stacking_key: Optional[StrictStr] = Field(None, alias="stackingKey", description="The key used to determine which stack to add the Task to")
    stack: Optional[Stack] = None
    __properties = ["id", "taskDefinitionId", "taskDefinitionVersion", "taskDefinitionDisplayName", "state", "ultimateParentTask", "parentTask", "childTasks", "correlationIds", "version", "terminalState", "asAtLastTransition", "fields", "stackingKey", "stack"]

    class Config:
        """Pydantic configuration"""
        allow_population_by_field_name = True
        validate_assignment = True

    def to_str(self) -> str:
        """Returns the string representation of the model using alias"""
        return pprint.pformat(self.dict(by_alias=True))

    def to_json(self) -> str:
        """Returns the JSON representation of the model using alias"""
        return json.dumps(self.to_dict())

    @classmethod
    def from_json(cls, json_str: str) -> Task:
        """Create an instance of Task from a JSON string"""
        return cls.from_dict(json.loads(json_str))

    def to_dict(self):
        """Returns the dictionary representation of the model using alias"""
        _dict = self.dict(by_alias=True,
                          exclude={
                          },
                          exclude_none=True)
        # override the default output from pydantic by calling `to_dict()` of task_definition_id
        if self.task_definition_id:
            _dict['taskDefinitionId'] = self.task_definition_id.to_dict()
        # override the default output from pydantic by calling `to_dict()` of task_definition_version
        if self.task_definition_version:
            _dict['taskDefinitionVersion'] = self.task_definition_version.to_dict()
        # override the default output from pydantic by calling `to_dict()` of ultimate_parent_task
        if self.ultimate_parent_task:
            _dict['ultimateParentTask'] = self.ultimate_parent_task.to_dict()
        # override the default output from pydantic by calling `to_dict()` of parent_task
        if self.parent_task:
            _dict['parentTask'] = self.parent_task.to_dict()
        # override the default output from pydantic by calling `to_dict()` of each item in child_tasks (list)
        _items = []
        if self.child_tasks:
            for _item in self.child_tasks:
                if _item:
                    _items.append(_item.to_dict())
            _dict['childTasks'] = _items
        # override the default output from pydantic by calling `to_dict()` of version
        if self.version:
            _dict['version'] = self.version.to_dict()
        # override the default output from pydantic by calling `to_dict()` of each item in fields (list)
        _items = []
        if self.fields:
            for _item in self.fields:
                if _item:
                    _items.append(_item.to_dict())
            _dict['fields'] = _items
        # override the default output from pydantic by calling `to_dict()` of stack
        if self.stack:
            _dict['stack'] = self.stack.to_dict()
        # set to None if child_tasks (nullable) is None
        # and __fields_set__ contains the field
        if self.child_tasks is None and "child_tasks" in self.__fields_set__:
            _dict['childTasks'] = None

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

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

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

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

        return _dict

    @classmethod
    def from_dict(cls, obj: dict) -> Task:
        """Create an instance of Task from a dict"""
        if obj is None:
            return None

        if not isinstance(obj, dict):
            return Task.parse_obj(obj)

        _obj = Task.parse_obj({
            "id": obj.get("id"),
            "task_definition_id": ResourceId.from_dict(obj.get("taskDefinitionId")) if obj.get("taskDefinitionId") is not None else None,
            "task_definition_version": TaskDefinitionVersion.from_dict(obj.get("taskDefinitionVersion")) if obj.get("taskDefinitionVersion") is not None else None,
            "task_definition_display_name": obj.get("taskDefinitionDisplayName"),
            "state": obj.get("state"),
            "ultimate_parent_task": TaskSummary.from_dict(obj.get("ultimateParentTask")) if obj.get("ultimateParentTask") is not None else None,
            "parent_task": TaskSummary.from_dict(obj.get("parentTask")) if obj.get("parentTask") is not None else None,
            "child_tasks": [TaskSummary.from_dict(_item) for _item in obj.get("childTasks")] if obj.get("childTasks") is not None else None,
            "correlation_ids": obj.get("correlationIds"),
            "version": VersionInfo.from_dict(obj.get("version")) if obj.get("version") is not None else None,
            "terminal_state": obj.get("terminalState"),
            "as_at_last_transition": obj.get("asAtLastTransition"),
            "fields": [TaskInstanceField.from_dict(_item) for _item in obj.get("fields")] if obj.get("fields") is not None else None,
            "stacking_key": obj.get("stackingKey"),
            "stack": Stack.from_dict(obj.get("stack")) if obj.get("stack") is not None else None
        })
        return _obj
