# coding: utf-8

"""
    Pulp 3 API

    Fetch, Upload, Organize, and Distribute Software Packages

    The version of the OpenAPI document: v3
    Contact: pulp-list@redhat.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 datetime import datetime
from pydantic import BaseModel, ConfigDict, Field, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from pulpcore.client.pulp_service.models.progress_report_response import ProgressReportResponse
from typing import Optional, Set
from typing_extensions import Self

class TaskResponse(BaseModel):
    """
    Base serializer for use with [pulpcore.app.models.Model][]  This ensures that all Serializers provide values for the 'pulp_href` field.  The class provides a default for the ``ref_name`` attribute in the ModelSerializers's ``Meta`` class. This ensures that the OpenAPI definitions of plugins are namespaced properly.
    """ # noqa: E501
    pulp_href: Optional[StrictStr] = None
    prn: Optional[StrictStr] = Field(default=None, description="The Pulp Resource Name (PRN).")
    pulp_created: Optional[datetime] = Field(default=None, description="Timestamp of creation.")
    pulp_last_updated: Optional[datetime] = Field(default=None, description="Timestamp of the last time this resource was updated. Note: for immutable resources - like content, repository versions, and publication - pulp_created and pulp_last_updated dates will be the same.")
    state: Optional[StrictStr] = Field(default=None, description="The current state of the task. The possible values include: 'waiting', 'skipped', 'running', 'completed', 'failed', 'canceled' and 'canceling'.")
    name: StrictStr = Field(description="The name of task.")
    logging_cid: StrictStr = Field(description="The logging correlation id associated with this task")
    created_by: Optional[StrictStr] = Field(default=None, description="User who dispatched this task.")
    unblocked_at: Optional[datetime] = Field(default=None, description="Timestamp of when this task was identified ready for pickup.")
    started_at: Optional[datetime] = Field(default=None, description="Timestamp of when this task started execution.")
    finished_at: Optional[datetime] = Field(default=None, description="Timestamp of when this task stopped execution.")
    error: Optional[Dict[str, Any]] = Field(default=None, description="A JSON Object of a fatal error encountered during the execution of this task.")
    worker: Optional[StrictStr] = Field(default=None, description="DEPRECATED - Always null")
    parent_task: Optional[StrictStr] = Field(default=None, description="The parent task that spawned this task.")
    child_tasks: Optional[List[StrictStr]] = Field(default=None, description="Any tasks spawned by this task.")
    task_group: Optional[StrictStr] = Field(default=None, description="The task group that this task is a member of.")
    progress_reports: Optional[List[ProgressReportResponse]] = None
    created_resources: Optional[List[StrictStr]] = Field(default=None, description="Resources created by this task.")
    reserved_resources_record: Optional[List[StrictStr]] = Field(default=None, description="A list of resources required by that task.")
    result: Optional[Any] = Field(default=None, description="The result of this task.")
    __properties: ClassVar[List[str]] = ["pulp_href", "prn", "pulp_created", "pulp_last_updated", "state", "name", "logging_cid", "created_by", "unblocked_at", "started_at", "finished_at", "error", "worker", "parent_task", "child_tasks", "task_group", "progress_reports", "created_resources", "reserved_resources_record", "result"]

    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 TaskResponse 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.
        * OpenAPI `readOnly` fields are excluded.
        * OpenAPI `readOnly` fields are excluded.
        * OpenAPI `readOnly` fields are excluded.
        * OpenAPI `readOnly` fields are excluded.
        * OpenAPI `readOnly` fields are excluded.
        * OpenAPI `readOnly` fields are excluded.
        * OpenAPI `readOnly` fields are excluded.
        * OpenAPI `readOnly` fields are excluded.
        * OpenAPI `readOnly` fields are excluded.
        * OpenAPI `readOnly` fields are excluded.
        * OpenAPI `readOnly` fields are excluded.
        * OpenAPI `readOnly` fields are excluded.
        * OpenAPI `readOnly` fields are excluded.
        * OpenAPI `readOnly` fields are excluded.
        * OpenAPI `readOnly` fields are excluded.
        * OpenAPI `readOnly` fields are excluded.
        * OpenAPI `readOnly` fields are excluded.
        * OpenAPI `readOnly` fields are excluded.
        """
        excluded_fields: Set[str] = set([
            "pulp_href",
            "prn",
            "pulp_created",
            "pulp_last_updated",
            "state",
            "created_by",
            "unblocked_at",
            "started_at",
            "finished_at",
            "error",
            "worker",
            "parent_task",
            "child_tasks",
            "task_group",
            "progress_reports",
            "created_resources",
            "reserved_resources_record",
            "result",
        ])

        _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 progress_reports (list)
        _items = []
        if self.progress_reports:
            for _item_progress_reports in self.progress_reports:
                if _item_progress_reports:
                    _items.append(_item_progress_reports.to_dict())
            _dict['progress_reports'] = _items
        # set to None if created_by (nullable) is None
        # and model_fields_set contains the field
        if self.created_by is None and "created_by" in self.model_fields_set:
            _dict['created_by'] = None

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

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

        return _dict

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

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

        _obj = cls.model_validate({
            "pulp_href": obj.get("pulp_href"),
            "prn": obj.get("prn"),
            "pulp_created": obj.get("pulp_created"),
            "pulp_last_updated": obj.get("pulp_last_updated"),
            "state": obj.get("state"),
            "name": obj.get("name"),
            "logging_cid": obj.get("logging_cid"),
            "created_by": obj.get("created_by"),
            "unblocked_at": obj.get("unblocked_at"),
            "started_at": obj.get("started_at"),
            "finished_at": obj.get("finished_at"),
            "error": obj.get("error"),
            "worker": obj.get("worker"),
            "parent_task": obj.get("parent_task"),
            "child_tasks": obj.get("child_tasks"),
            "task_group": obj.get("task_group"),
            "progress_reports": [ProgressReportResponse.from_dict(_item) for _item in obj["progress_reports"]] if obj.get("progress_reports") is not None else None,
            "created_resources": obj.get("created_resources"),
            "reserved_resources_record": obj.get("reserved_resources_record"),
            "result": obj.get("result")
        })
        return _obj


