from pubtools.pulplib._impl import compat_attr as attr

from ..schema import load_schema
from .common import PulpObject
from .attr import pulp_attrib


@attr.s(kw_only=True, frozen=True)
class Task(PulpObject):
    """Represents a Pulp task."""

    _SCHEMA = load_schema("task")

    id = pulp_attrib(type=str, pulp_field="id")
    """ID of this task (str)."""

    completed = attr.ib(default=None, type=bool)
    """True if this task has completed, successfully or otherwise.

    May be `None` if the state of this task is unknown.
    """

    succeeded = attr.ib(default=None, type=bool)
    """True if this task has completed successfully.

    May be `None` if the state of this task is unknown.
    """

    error_summary = attr.ib(default=None, type=str)
    """A summary of the reason for this task's failure (if any).

    This is a short string, generally a single line, suitable for display to users.
    """

    error_details = attr.ib(default=None, type=str)
    """Detailed information for this task's failure (if any).

    This may be a multi-line string and may include technical information such as
    a Python backtrace generated by Pulp.
    """

    @succeeded.validator
    def _check_succeeded(self, _, value):
        if value and not self.completed:
            raise ValueError("Cannot have task with completed=False, succeeded=True")

    @classmethod
    def _data_to_init_args(cls, data):
        # todo: error_* attribs
        state = data["state"]
        return {
            "id": data["task_id"],
            "completed": state in ("finished", "error", "canceled", "skipped"),
            "succeeded": state in ("finished", "skipped"),
        }
