# This is spectacularly generated code by spectacular based on
# Qlik Cloud Services APIs

from __future__ import annotations

from dataclasses import asdict, dataclass
from typing import Literal

from ..auth import Auth, Config
from ..listable import ListableResource


@dataclass
class AutomationDetailResponseObject:
    """

    Attributes
    ----------
    connectorIds: list[str]
      A list of connectors used inside the workspace.
    createdAt: str
    description: str
    endpointIds: list[str]
      A list of endpoints used inside the workspace.
    executionToken: str
    id: str
    lastRun: RunDetailResponseObject
    lastRunAt: str
    lastRunStatus: Literal["failed", "finished", "finished with warnings", "must stop", "not started", "paused", "running", "starting", "stopped"]
    name: str
    ownerId: str
    runMode: Literal["manual", "scheduled", "triggered", "webhook"]
    schedules: list[ScheduleResponseObject]
    snippetIds: list[str]
      A list of snippets used inside the workspace.
    state: Literal["available", "unavailable", "disabled"]
    updatedAt: str
    workspace: object
      The workspace generated by the Qlik Application Automations editor.
    """

    connectorIds: list[str] = None
    createdAt: str = None
    description: str = None
    endpointIds: list[str] = None
    executionToken: str = None
    id: str = None
    lastRun: RunDetailResponseObject = None
    lastRunAt: str = None
    lastRunStatus: Literal[
        "failed",
        "finished",
        "finished with warnings",
        "must stop",
        "not started",
        "paused",
        "running",
        "starting",
        "stopped",
    ] = None
    name: str = None
    ownerId: str = None
    runMode: Literal["manual", "scheduled", "triggered", "webhook"] = None
    schedules: list[ScheduleResponseObject] = None
    snippetIds: list[str] = None
    state: Literal["available", "unavailable", "disabled"] = "available"
    updatedAt: str = None
    workspace: object = None

    def __init__(self_, **kvargs):
        if "connectorIds" in kvargs and kvargs["connectorIds"] is not None:
            self_.connectorIds = kvargs["connectorIds"]
        if "createdAt" in kvargs and kvargs["createdAt"] is not None:
            self_.createdAt = kvargs["createdAt"]
        if "description" in kvargs and kvargs["description"] is not None:
            self_.description = kvargs["description"]
        if "endpointIds" in kvargs and kvargs["endpointIds"] is not None:
            self_.endpointIds = kvargs["endpointIds"]
        if "executionToken" in kvargs and kvargs["executionToken"] is not None:
            self_.executionToken = kvargs["executionToken"]
        if "id" in kvargs and kvargs["id"] is not None:
            self_.id = kvargs["id"]
        if "lastRun" in kvargs and kvargs["lastRun"] is not None:
            if (
                type(kvargs["lastRun"]).__name__
                == AutomationDetailResponseObject.__annotations__["lastRun"]
            ):
                self_.lastRun = kvargs["lastRun"]
            else:
                self_.lastRun = RunDetailResponseObject(**kvargs["lastRun"])
        if "lastRunAt" in kvargs and kvargs["lastRunAt"] is not None:
            self_.lastRunAt = kvargs["lastRunAt"]
        if "lastRunStatus" in kvargs and kvargs["lastRunStatus"] is not None:
            self_.lastRunStatus = kvargs["lastRunStatus"]
        if "name" in kvargs and kvargs["name"] is not None:
            self_.name = kvargs["name"]
        if "ownerId" in kvargs and kvargs["ownerId"] is not None:
            self_.ownerId = kvargs["ownerId"]
        if "runMode" in kvargs and kvargs["runMode"] is not None:
            self_.runMode = kvargs["runMode"]
        if "schedules" in kvargs and kvargs["schedules"] is not None:
            if all(
                f"list[{type(e).__name__}]"
                == AutomationDetailResponseObject.__annotations__["schedules"]
                for e in kvargs["schedules"]
            ):
                self_.schedules = kvargs["schedules"]
            else:
                self_.schedules = [
                    ScheduleResponseObject(**e) for e in kvargs["schedules"]
                ]
        if "snippetIds" in kvargs and kvargs["snippetIds"] is not None:
            self_.snippetIds = kvargs["snippetIds"]
        if "state" in kvargs and kvargs["state"] is not None:
            self_.state = kvargs["state"]
        if "updatedAt" in kvargs and kvargs["updatedAt"] is not None:
            self_.updatedAt = kvargs["updatedAt"]
        if "workspace" in kvargs and kvargs["workspace"] is not None:
            self_.workspace = kvargs["workspace"]
        for k0, v in kvargs.items():
            k = k0.replace("-", "_")
            if k not in getattr(self_, "__annotations__", {}):
                self_.__setattr__(k, v)

    def copy(self, name: str = None) -> object:
        """
        Copy an automation.

        Parameters
        ----------
        name: str = None
          Name of the new automation.
        """
        data = {"name": name}
        response = self.auth.rest(
            path="/automations/{id}/actions/copy".replace("{id}", self.id),
            method="POST",
            params={},
            data=data,
        )
        return response.json()

    def disable(self) -> None:
        """
        Disables an automation.

        Parameters
        ----------
        """
        self.auth.rest(
            path="/automations/{id}/actions/disable".replace("{id}", self.id),
            method="POST",
            params={},
            data=None,
        )

    def enable(self) -> None:
        """
        Enable an automation.

        Parameters
        ----------
        """
        self.auth.rest(
            path="/automations/{id}/actions/enable".replace("{id}", self.id),
            method="POST",
            params={},
            data=None,
        )

    def move(self, userId: str = None) -> None:
        """
        Move an automation to a different user.
        This step will remove the history and change logs of this automation. All linked connections used inside an automation will be detached.

        Parameters
        ----------
        userId: str = None
        """
        data = {"userId": userId}
        self.auth.rest(
            path="/automations/{id}/actions/move".replace("{id}", self.id),
            method="POST",
            params={},
            data=data,
        )

    def export_run(self, runId: str) -> object:
        """
        Export a run.
        Creates a temporary pre-signed AWS S3 URL to download the raw logs of a completed run. This URL is valid for 5 minutes.

        Parameters
        ----------
        runId: str
          The unique identifier for the run.
        """
        response = self.auth.rest(
            path="/automations/{id}/runs/{runId}/actions/export".replace(
                "{id}", self.id
            ).replace("{runId}", runId),
            method="POST",
            params={},
            data=None,
        )
        return response.json()

    def retry_run(self, runId: str) -> None:
        """
        Retry a run.
        This action allows you to retry a specific run by creating a new run using the same inputs.

        Parameters
        ----------
        runId: str
          The unique identifier for the run.
        """
        self.auth.rest(
            path="/automations/{id}/runs/{runId}/actions/retry".replace(
                "{id}", self.id
            ).replace("{runId}", runId),
            method="POST",
            params={},
            data=None,
        )

    def stop_run(self, runId: str) -> None:
        """
        Stop a running automation.
        Force a run to be stopped immediately.

        Parameters
        ----------
        runId: str
          The unique identifier for the run.
        """
        self.auth.rest(
            path="/automations/{id}/runs/{runId}/actions/stop".replace(
                "{id}", self.id
            ).replace("{runId}", runId),
            method="POST",
            params={},
            data=None,
        )

    def get_run(self, runId: str) -> RunDetailResponseObject:
        """
        Retrieves a run

        Parameters
        ----------
        runId: str
          The unique identifier for the run.
        """
        response = self.auth.rest(
            path="/automations/{id}/runs/{runId}".replace("{id}", self.id).replace(
                "{runId}", runId
            ),
            method="GET",
            params={},
            data=None,
        )
        obj = RunDetailResponseObject(**response.json())
        obj.auth = self.auth
        return obj

    def get_runs(
        self,
        filter: str = None,
        limit: int = 10,
        sort: Literal[
            "id",
            "status",
            "startTime",
            "-id",
            "-status",
            "-startTime",
            "+id",
            "+status",
            "+startTime",
        ] = "id",
    ) -> ListableResource[RunListObject]:
        """
        Retrieves a list of runs for a specific automation.

        Parameters
        ----------
        filter: str = None
          Allowed filters: status, context, startTime and title
        limit: int = 10
          The number of runs to retrieve.
        sort: Literal["id", "status", "startTime", "-id", "-status", "-startTime", "+id", "+status", "+startTime"] = "id"
          The field to sort by, with +- prefix indicating sort order. (?query=-startTime => sort on the startTime field using descending order)
        """
        query_params = {}
        if filter is not None:
            query_params["filter"] = filter
        if limit is not None:
            query_params["limit"] = limit
        if sort is not None:
            query_params["sort"] = sort
        response = self.auth.rest(
            path="/automations/{id}/runs".replace("{id}", self.id),
            method="GET",
            params=query_params,
            data=None,
        )
        return ListableResource(
            response=response.json(),
            cls=RunListObject,
            auth=self.auth,
            path="/automations/{id}/runs".replace("{id}", self.id),
            query_params=query_params,
        )

    def create_run(self, data: RunDetailRequestObject) -> RunDetailResponseObject:
        """
        Create a run

        Parameters
        ----------
        data: RunDetailRequestObject
          Run object to create
        """
        if data is not None:
            try:
                data = asdict(data)
            except:
                data = data
        response = self.auth.rest(
            path="/automations/{id}/runs".replace("{id}", self.id),
            method="POST",
            params={},
            data=data,
        )
        obj = RunDetailResponseObject(**response.json())
        obj.auth = self.auth
        return obj

    def delete(self) -> None:
        """
        Delete an automation

        Parameters
        ----------
        """
        self.auth.rest(
            path="/automations/{id}".replace("{id}", self.id),
            method="DELETE",
            params={},
            data=None,
        )

    def set(
        self, data: AutomationDetailRequestObject
    ) -> AutomationDetailResponseObject:
        """
        Update an automation

        Parameters
        ----------
        data: AutomationDetailRequestObject
          Automation object to update
        """
        if data is not None:
            try:
                data = asdict(data)
            except:
                data = data
        response = self.auth.rest(
            path="/automations/{id}".replace("{id}", self.id),
            method="PUT",
            params={},
            data=data,
        )
        self.__init__(**response.json())
        return self


@dataclass
class AutomationDetailRequestObject:
    """

    Attributes
    ----------
    description: str
    name: str
    schedules: list[ScheduleRequestObject]
    state: Literal["available", "unavailable", "disabled"]
    workspace: object
      The workspace generated by the Qlik Application Automations editor.
    """

    description: str = None
    name: str = None
    schedules: list[ScheduleRequestObject] = None
    state: Literal["available", "unavailable", "disabled"] = "available"
    workspace: object = None

    def __init__(self_, **kvargs):
        if "description" in kvargs and kvargs["description"] is not None:
            self_.description = kvargs["description"]
        if "name" in kvargs and kvargs["name"] is not None:
            self_.name = kvargs["name"]
        if "schedules" in kvargs and kvargs["schedules"] is not None:
            if all(
                f"list[{type(e).__name__}]"
                == AutomationDetailRequestObject.__annotations__["schedules"]
                for e in kvargs["schedules"]
            ):
                self_.schedules = kvargs["schedules"]
            else:
                self_.schedules = [
                    ScheduleRequestObject(**e) for e in kvargs["schedules"]
                ]
        if "state" in kvargs and kvargs["state"] is not None:
            self_.state = kvargs["state"]
        if "workspace" in kvargs and kvargs["workspace"] is not None:
            self_.workspace = kvargs["workspace"]
        for k0, v in kvargs.items():
            k = k0.replace("-", "_")
            if k not in getattr(self_, "__annotations__", {}):
                self_.__setattr__(k, v)


@dataclass
class AutomationList:
    """

    Attributes
    ----------
    data: list[AutomationListObject]
    links: Links
    """

    data: list[AutomationListObject] = None
    links: Links = None

    def __init__(self_, **kvargs):
        if "data" in kvargs and kvargs["data"] is not None:
            if all(
                f"list[{type(e).__name__}]" == AutomationList.__annotations__["data"]
                for e in kvargs["data"]
            ):
                self_.data = kvargs["data"]
            else:
                self_.data = [AutomationListObject(**e) for e in kvargs["data"]]
        if "links" in kvargs and kvargs["links"] is not None:
            if (
                type(kvargs["links"]).__name__
                == AutomationList.__annotations__["links"]
            ):
                self_.links = kvargs["links"]
            else:
                self_.links = Links(**kvargs["links"])
        for k0, v in kvargs.items():
            k = k0.replace("-", "_")
            if k not in getattr(self_, "__annotations__", {}):
                self_.__setattr__(k, v)


@dataclass
class AutomationListObject:
    """

    Attributes
    ----------
    createdAt: str
    description: str
    id: str
    lastRunAt: str
    lastRunStatus: Literal["failed", "finished", "finished with warnings", "must stop", "not started", "paused", "running", "starting", "stopped"]
    name: str
    ownerId: str
    runMode: Literal["manual", "scheduled", "triggered", "webhook"]
    state: Literal["available", "unavailable", "disabled"]
    updatedAt: str
    """

    createdAt: str = None
    description: str = None
    id: str = None
    lastRunAt: str = None
    lastRunStatus: Literal[
        "failed",
        "finished",
        "finished with warnings",
        "must stop",
        "not started",
        "paused",
        "running",
        "starting",
        "stopped",
    ] = None
    name: str = None
    ownerId: str = None
    runMode: Literal["manual", "scheduled", "triggered", "webhook"] = None
    state: Literal["available", "unavailable", "disabled"] = "available"
    updatedAt: str = None

    def __init__(self_, **kvargs):
        if "createdAt" in kvargs and kvargs["createdAt"] is not None:
            self_.createdAt = kvargs["createdAt"]
        if "description" in kvargs and kvargs["description"] is not None:
            self_.description = kvargs["description"]
        if "id" in kvargs and kvargs["id"] is not None:
            self_.id = kvargs["id"]
        if "lastRunAt" in kvargs and kvargs["lastRunAt"] is not None:
            self_.lastRunAt = kvargs["lastRunAt"]
        if "lastRunStatus" in kvargs and kvargs["lastRunStatus"] is not None:
            self_.lastRunStatus = kvargs["lastRunStatus"]
        if "name" in kvargs and kvargs["name"] is not None:
            self_.name = kvargs["name"]
        if "ownerId" in kvargs and kvargs["ownerId"] is not None:
            self_.ownerId = kvargs["ownerId"]
        if "runMode" in kvargs and kvargs["runMode"] is not None:
            self_.runMode = kvargs["runMode"]
        if "state" in kvargs and kvargs["state"] is not None:
            self_.state = kvargs["state"]
        if "updatedAt" in kvargs and kvargs["updatedAt"] is not None:
            self_.updatedAt = kvargs["updatedAt"]
        for k0, v in kvargs.items():
            k = k0.replace("-", "_")
            if k not in getattr(self_, "__annotations__", {}):
                self_.__setattr__(k, v)


@dataclass
class AutomationUsageObject:
    """

    Attributes
    ----------
    guid: str
      The unique identifier for the automation.
    name: str
      The name for the automation.
    ownerId: str
      The unique identifier for the user who owns the automation
    """

    guid: str = None
    name: str = None
    ownerId: str = None

    def __init__(self_, **kvargs):
        if "guid" in kvargs and kvargs["guid"] is not None:
            self_.guid = kvargs["guid"]
        if "name" in kvargs and kvargs["name"] is not None:
            self_.name = kvargs["name"]
        if "ownerId" in kvargs and kvargs["ownerId"] is not None:
            self_.ownerId = kvargs["ownerId"]
        for k0, v in kvargs.items():
            k = k0.replace("-", "_")
            if k not in getattr(self_, "__annotations__", {}):
                self_.__setattr__(k, v)


@dataclass
class Links:
    """

    Attributes
    ----------
    next: PaginationLink
    prev: PaginationLink
    """

    next: PaginationLink = None
    prev: PaginationLink = None

    def __init__(self_, **kvargs):
        if "next" in kvargs and kvargs["next"] is not None:
            if type(kvargs["next"]).__name__ == Links.__annotations__["next"]:
                self_.next = kvargs["next"]
            else:
                self_.next = PaginationLink(**kvargs["next"])
        if "prev" in kvargs and kvargs["prev"] is not None:
            if type(kvargs["prev"]).__name__ == Links.__annotations__["prev"]:
                self_.prev = kvargs["prev"]
            else:
                self_.prev = PaginationLink(**kvargs["prev"])
        for k0, v in kvargs.items():
            k = k0.replace("-", "_")
            if k not in getattr(self_, "__annotations__", {}):
                self_.__setattr__(k, v)


@dataclass
class PaginationLink:
    """

    Attributes
    ----------
    href: str
      The URL to a resource request
    """

    href: str = None

    def __init__(self_, **kvargs):
        if "href" in kvargs and kvargs["href"] is not None:
            self_.href = kvargs["href"]
        for k0, v in kvargs.items():
            k = k0.replace("-", "_")
            if k not in getattr(self_, "__annotations__", {}):
                self_.__setattr__(k, v)


@dataclass
class RunDetailRequestObject:
    """

    Attributes
    ----------
    context: Literal["api"]
      The source that triggers the automation will set the context.
    id: str
    inputs: object
    """

    context: Literal["api"] = None
    id: str = None
    inputs: object = None

    def __init__(self_, **kvargs):
        if "context" in kvargs and kvargs["context"] is not None:
            self_.context = kvargs["context"]
        if "id" in kvargs and kvargs["id"] is not None:
            self_.id = kvargs["id"]
        if "inputs" in kvargs and kvargs["inputs"] is not None:
            self_.inputs = kvargs["inputs"]
        for k0, v in kvargs.items():
            k = k0.replace("-", "_")
            if k not in getattr(self_, "__annotations__", {}):
                self_.__setattr__(k, v)


@dataclass
class RunDetailResponseObject:
    """

    Attributes
    ----------
    context: Literal["test_run", "editor", "detail", "api_sync", "api_async", "webhook", "lookup"]
      The source that triggers the automation will set the context. Certain contexts impact the execution of an automation (for example, The "test_run" context will not process all results when listing items).
    createdAt: str
    error: object
    expectedInputs: object
    id: str
    inputs: object
    isArchived: bool
    isTestRun: bool
    metrics: RunDetailResponseObjectMetrics
    scheduledStartTime: str
    startTime: str
    status: Literal["failed", "finished", "finished with warnings", "must stop", "not started", "running", "starting", "stopped"]
    stopTime: str
    title: str
    updatedAt: str
    """

    context: Literal[
        "test_run", "editor", "detail", "api_sync", "api_async", "webhook", "lookup"
    ] = None
    createdAt: str = None
    error: object = None
    expectedInputs: object = None
    id: str = None
    inputs: object = None
    isArchived: bool = None
    isTestRun: bool = None
    metrics: RunDetailResponseObjectMetrics = None
    scheduledStartTime: str = None
    startTime: str = None
    status: Literal[
        "failed",
        "finished",
        "finished with warnings",
        "must stop",
        "not started",
        "running",
        "starting",
        "stopped",
    ] = None
    stopTime: str = None
    title: str = None
    updatedAt: str = None

    def __init__(self_, **kvargs):
        if "context" in kvargs and kvargs["context"] is not None:
            self_.context = kvargs["context"]
        if "createdAt" in kvargs and kvargs["createdAt"] is not None:
            self_.createdAt = kvargs["createdAt"]
        if "error" in kvargs and kvargs["error"] is not None:
            self_.error = kvargs["error"]
        if "expectedInputs" in kvargs and kvargs["expectedInputs"] is not None:
            self_.expectedInputs = kvargs["expectedInputs"]
        if "id" in kvargs and kvargs["id"] is not None:
            self_.id = kvargs["id"]
        if "inputs" in kvargs and kvargs["inputs"] is not None:
            self_.inputs = kvargs["inputs"]
        if "isArchived" in kvargs and kvargs["isArchived"] is not None:
            self_.isArchived = kvargs["isArchived"]
        if "isTestRun" in kvargs and kvargs["isTestRun"] is not None:
            self_.isTestRun = kvargs["isTestRun"]
        if "metrics" in kvargs and kvargs["metrics"] is not None:
            if (
                type(kvargs["metrics"]).__name__
                == RunDetailResponseObject.__annotations__["metrics"]
            ):
                self_.metrics = kvargs["metrics"]
            else:
                self_.metrics = RunDetailResponseObjectMetrics(**kvargs["metrics"])
        if "scheduledStartTime" in kvargs and kvargs["scheduledStartTime"] is not None:
            self_.scheduledStartTime = kvargs["scheduledStartTime"]
        if "startTime" in kvargs and kvargs["startTime"] is not None:
            self_.startTime = kvargs["startTime"]
        if "status" in kvargs and kvargs["status"] is not None:
            self_.status = kvargs["status"]
        if "stopTime" in kvargs and kvargs["stopTime"] is not None:
            self_.stopTime = kvargs["stopTime"]
        if "title" in kvargs and kvargs["title"] is not None:
            self_.title = kvargs["title"]
        if "updatedAt" in kvargs and kvargs["updatedAt"] is not None:
            self_.updatedAt = kvargs["updatedAt"]
        for k0, v in kvargs.items():
            k = k0.replace("-", "_")
            if k not in getattr(self_, "__annotations__", {}):
                self_.__setattr__(k, v)


@dataclass
class RunDetailResponseObjectMetrics:
    """

    Attributes
    ----------
    blocks: list[RunDetailResponseObjectMetricsBlocks]
      List of blocks used during execution. Note: this list currently only contains endpointBlocks and snippetBlocks
    network: RunDetailResponseObjectMetricsNetwork
    totalApiCalls: int
      The number of API calls made.
    """

    blocks: list[RunDetailResponseObjectMetricsBlocks] = None
    network: RunDetailResponseObjectMetricsNetwork = None
    totalApiCalls: int = None

    def __init__(self_, **kvargs):
        if "blocks" in kvargs and kvargs["blocks"] is not None:
            if all(
                f"list[{type(e).__name__}]"
                == RunDetailResponseObjectMetrics.__annotations__["blocks"]
                for e in kvargs["blocks"]
            ):
                self_.blocks = kvargs["blocks"]
            else:
                self_.blocks = [
                    RunDetailResponseObjectMetricsBlocks(**e) for e in kvargs["blocks"]
                ]
        if "network" in kvargs and kvargs["network"] is not None:
            if (
                type(kvargs["network"]).__name__
                == RunDetailResponseObjectMetrics.__annotations__["network"]
            ):
                self_.network = kvargs["network"]
            else:
                self_.network = RunDetailResponseObjectMetricsNetwork(
                    **kvargs["network"]
                )
        if "totalApiCalls" in kvargs and kvargs["totalApiCalls"] is not None:
            self_.totalApiCalls = kvargs["totalApiCalls"]
        for k0, v in kvargs.items():
            k = k0.replace("-", "_")
            if k not in getattr(self_, "__annotations__", {}):
                self_.__setattr__(k, v)


@dataclass
class RunDetailResponseObjectMetricsBlocks:
    """
    Information of the ended execution per block.

    Attributes
    ----------
    apiCalls: int
      API calls to external resources made by the current block.
    connectorId: str
      Unique identifier for the connector used within the block of the execution.
    endpointId: str
      Unique identifier for the snippet block used within the execution.
    rxBytes: int
      Total amount of received bytes sent by the current block.
    snippetId: str
      Unique identifier for the snippet block used within the execution.
    txBytes: int
      Total amount of sent bytes sent by the current block.
    type: Literal["snippetBlock", "endpointBlock"]
      Type of the block.
    """

    apiCalls: int = None
    connectorId: str = None
    endpointId: str = None
    rxBytes: int = None
    snippetId: str = None
    txBytes: int = None
    type: Literal["snippetBlock", "endpointBlock"] = None

    def __init__(self_, **kvargs):
        if "apiCalls" in kvargs and kvargs["apiCalls"] is not None:
            self_.apiCalls = kvargs["apiCalls"]
        if "connectorId" in kvargs and kvargs["connectorId"] is not None:
            self_.connectorId = kvargs["connectorId"]
        if "endpointId" in kvargs and kvargs["endpointId"] is not None:
            self_.endpointId = kvargs["endpointId"]
        if "rxBytes" in kvargs and kvargs["rxBytes"] is not None:
            self_.rxBytes = kvargs["rxBytes"]
        if "snippetId" in kvargs and kvargs["snippetId"] is not None:
            self_.snippetId = kvargs["snippetId"]
        if "txBytes" in kvargs and kvargs["txBytes"] is not None:
            self_.txBytes = kvargs["txBytes"]
        if "type" in kvargs and kvargs["type"] is not None:
            self_.type = kvargs["type"]
        for k0, v in kvargs.items():
            k = k0.replace("-", "_")
            if k not in getattr(self_, "__annotations__", {}):
                self_.__setattr__(k, v)


@dataclass
class RunDetailResponseObjectMetricsNetwork:
    """

    Attributes
    ----------
    rxBytes: int
      The number of received bytes.
    txBytes: int
      The number of received bytes.
    """

    rxBytes: int = None
    txBytes: int = None

    def __init__(self_, **kvargs):
        if "rxBytes" in kvargs and kvargs["rxBytes"] is not None:
            self_.rxBytes = kvargs["rxBytes"]
        if "txBytes" in kvargs and kvargs["txBytes"] is not None:
            self_.txBytes = kvargs["txBytes"]
        for k0, v in kvargs.items():
            k = k0.replace("-", "_")
            if k not in getattr(self_, "__annotations__", {}):
                self_.__setattr__(k, v)


@dataclass
class RunList:
    """

    Attributes
    ----------
    data: list[RunListObject]
    links: Links
    """

    data: list[RunListObject] = None
    links: Links = None

    def __init__(self_, **kvargs):
        if "data" in kvargs and kvargs["data"] is not None:
            if all(
                f"list[{type(e).__name__}]" == RunList.__annotations__["data"]
                for e in kvargs["data"]
            ):
                self_.data = kvargs["data"]
            else:
                self_.data = [RunListObject(**e) for e in kvargs["data"]]
        if "links" in kvargs and kvargs["links"] is not None:
            if type(kvargs["links"]).__name__ == RunList.__annotations__["links"]:
                self_.links = kvargs["links"]
            else:
                self_.links = Links(**kvargs["links"])
        for k0, v in kvargs.items():
            k = k0.replace("-", "_")
            if k not in getattr(self_, "__annotations__", {}):
                self_.__setattr__(k, v)


@dataclass
class RunListObject:
    """

    Attributes
    ----------
    context: Literal["test_run", "editor", "detail", "api_sync", "api_async", "webhook", "lookup"]
    createdAt: str
    error: object
    id: str
    isArchived: bool
    isTestRun: bool
    scheduledStartTime: str
    startTime: str
    status: Literal["failed", "finished", "finished with warnings", "must stop", "not started", "running", "starting", "stopped"]
    stopTime: str
    title: str
    updatedAt: str
    """

    context: Literal[
        "test_run", "editor", "detail", "api_sync", "api_async", "webhook", "lookup"
    ] = None
    createdAt: str = None
    error: object = None
    id: str = None
    isArchived: bool = None
    isTestRun: bool = None
    scheduledStartTime: str = None
    startTime: str = None
    status: Literal[
        "failed",
        "finished",
        "finished with warnings",
        "must stop",
        "not started",
        "running",
        "starting",
        "stopped",
    ] = None
    stopTime: str = None
    title: str = None
    updatedAt: str = None

    def __init__(self_, **kvargs):
        if "context" in kvargs and kvargs["context"] is not None:
            self_.context = kvargs["context"]
        if "createdAt" in kvargs and kvargs["createdAt"] is not None:
            self_.createdAt = kvargs["createdAt"]
        if "error" in kvargs and kvargs["error"] is not None:
            self_.error = kvargs["error"]
        if "id" in kvargs and kvargs["id"] is not None:
            self_.id = kvargs["id"]
        if "isArchived" in kvargs and kvargs["isArchived"] is not None:
            self_.isArchived = kvargs["isArchived"]
        if "isTestRun" in kvargs and kvargs["isTestRun"] is not None:
            self_.isTestRun = kvargs["isTestRun"]
        if "scheduledStartTime" in kvargs and kvargs["scheduledStartTime"] is not None:
            self_.scheduledStartTime = kvargs["scheduledStartTime"]
        if "startTime" in kvargs and kvargs["startTime"] is not None:
            self_.startTime = kvargs["startTime"]
        if "status" in kvargs and kvargs["status"] is not None:
            self_.status = kvargs["status"]
        if "stopTime" in kvargs and kvargs["stopTime"] is not None:
            self_.stopTime = kvargs["stopTime"]
        if "title" in kvargs and kvargs["title"] is not None:
            self_.title = kvargs["title"]
        if "updatedAt" in kvargs and kvargs["updatedAt"] is not None:
            self_.updatedAt = kvargs["updatedAt"]
        for k0, v in kvargs.items():
            k = k0.replace("-", "_")
            if k not in getattr(self_, "__annotations__", {}):
                self_.__setattr__(k, v)


@dataclass
class ScheduleRequestObject:
    """

    Attributes
    ----------
    interval: int
      time in seconds.
    startAt: str
    stopAt: str
    timezone: str
    """

    interval: int = None
    startAt: str = None
    stopAt: str = None
    timezone: str = None

    def __init__(self_, **kvargs):
        if "interval" in kvargs and kvargs["interval"] is not None:
            self_.interval = kvargs["interval"]
        if "startAt" in kvargs and kvargs["startAt"] is not None:
            self_.startAt = kvargs["startAt"]
        if "stopAt" in kvargs and kvargs["stopAt"] is not None:
            self_.stopAt = kvargs["stopAt"]
        if "timezone" in kvargs and kvargs["timezone"] is not None:
            self_.timezone = kvargs["timezone"]
        for k0, v in kvargs.items():
            k = k0.replace("-", "_")
            if k not in getattr(self_, "__annotations__", {}):
                self_.__setattr__(k, v)


@dataclass
class ScheduleResponseObject:
    """

    Attributes
    ----------
    id: str
    interval: int
      time in seconds.
    lastStartedAt: str
    startAt: str
    stopAt: str
    timezone: str
    """

    id: str = None
    interval: int = None
    lastStartedAt: str = None
    startAt: str = None
    stopAt: str = None
    timezone: str = None

    def __init__(self_, **kvargs):
        if "id" in kvargs and kvargs["id"] is not None:
            self_.id = kvargs["id"]
        if "interval" in kvargs and kvargs["interval"] is not None:
            self_.interval = kvargs["interval"]
        if "lastStartedAt" in kvargs and kvargs["lastStartedAt"] is not None:
            self_.lastStartedAt = kvargs["lastStartedAt"]
        if "startAt" in kvargs and kvargs["startAt"] is not None:
            self_.startAt = kvargs["startAt"]
        if "stopAt" in kvargs and kvargs["stopAt"] is not None:
            self_.stopAt = kvargs["stopAt"]
        if "timezone" in kvargs and kvargs["timezone"] is not None:
            self_.timezone = kvargs["timezone"]
        for k0, v in kvargs.items():
            k = k0.replace("-", "_")
            if k not in getattr(self_, "__annotations__", {}):
                self_.__setattr__(k, v)


@dataclass
class SettingsObject:
    """

    Attributes
    ----------
    automationsEnabled: bool
    """

    automationsEnabled: bool = None

    def __init__(self_, **kvargs):
        if "automationsEnabled" in kvargs and kvargs["automationsEnabled"] is not None:
            self_.automationsEnabled = kvargs["automationsEnabled"]
        for k0, v in kvargs.items():
            k = k0.replace("-", "_")
            if k not in getattr(self_, "__annotations__", {}):
                self_.__setattr__(k, v)


@dataclass
class UsageList:
    """

    Attributes
    ----------
    data: list[UsageObject]
    """

    data: list[UsageObject] = None

    def __init__(self_, **kvargs):
        if "data" in kvargs and kvargs["data"] is not None:
            if all(
                f"list[{type(e).__name__}]" == UsageList.__annotations__["data"]
                for e in kvargs["data"]
            ):
                self_.data = kvargs["data"]
            else:
                self_.data = [UsageObject(**e) for e in kvargs["data"]]
        for k0, v in kvargs.items():
            k = k0.replace("-", "_")
            if k not in getattr(self_, "__annotations__", {}):
                self_.__setattr__(k, v)


@dataclass
class UsageObject:
    """

    Attributes
    ----------
    automation: AutomationUsageObject
    date: str
      The date for the metric
    name: Literal["runs", "scheduledRun", "triggeredRun", "webhookRuns", "duration", "bandwidthIn", "bandwidthOut"]
      The name for the metric
    value: int
      The value count of the metric
    """

    automation: AutomationUsageObject = None
    date: str = None
    name: Literal[
        "runs",
        "scheduledRun",
        "triggeredRun",
        "webhookRuns",
        "duration",
        "bandwidthIn",
        "bandwidthOut",
    ] = None
    value: int = None

    def __init__(self_, **kvargs):
        if "automation" in kvargs and kvargs["automation"] is not None:
            if (
                type(kvargs["automation"]).__name__
                == UsageObject.__annotations__["automation"]
            ):
                self_.automation = kvargs["automation"]
            else:
                self_.automation = AutomationUsageObject(**kvargs["automation"])
        if "date" in kvargs and kvargs["date"] is not None:
            self_.date = kvargs["date"]
        if "name" in kvargs and kvargs["name"] is not None:
            self_.name = kvargs["name"]
        if "value" in kvargs and kvargs["value"] is not None:
            self_.value = kvargs["value"]
        for k0, v in kvargs.items():
            k = k0.replace("-", "_")
            if k not in getattr(self_, "__annotations__", {}):
                self_.__setattr__(k, v)


class Automations:
    def __init__(self, config: Config) -> None:
        self.config = config
        self.auth = Auth(config)

    def get_settings(self) -> SettingsObject:
        """
        Retrieves the automation settings.

        Parameters
        ----------
        """
        response = self.auth.rest(
            path="/automations/settings",
            method="GET",
            params={},
            data=None,
        )
        obj = SettingsObject(**response.json())
        obj.auth = self.auth
        return obj

    def set_settings(self, data: SettingsObject) -> SettingsObject:
        """
        Update the automation settings.

        Parameters
        ----------
        data: SettingsObject
        """
        if data is not None:
            try:
                data = asdict(data)
            except:
                data = data
        response = self.auth.rest(
            path="/automations/settings",
            method="PUT",
            params={},
            data=data,
        )
        obj = SettingsObject(**response.json())
        obj.auth = self.auth
        return obj

    def get_usages(self, filter: str, breakdownBy: str = None) -> UsageList:
        """
        Retrieves all automation usage for a tenant
        Limitations:
         * Maximum 1000 metrics per API call

        Parameters
        ----------
        filter: str
          Indicates how the metrics should be filtered
        breakdownBy: str = None
          If specified, result will be broken apart for each automation
        """
        query_params = {}
        if filter is not None:
            query_params["filter"] = filter
        if breakdownBy is not None:
            query_params["breakdownBy"] = breakdownBy
        response = self.auth.rest(
            path="/automations/usage",
            method="GET",
            params=query_params,
            data=None,
        )
        obj = UsageList(**response.json())
        obj.auth = self.auth
        return obj

    def get(self, id: str) -> AutomationDetailResponseObject:
        """
        Retrieves an automation

        Parameters
        ----------
        id: str
          The unique identifier for the automation.
        """
        response = self.auth.rest(
            path="/automations/{id}".replace("{id}", id),
            method="GET",
            params={},
            data=None,
        )
        obj = AutomationDetailResponseObject(**response.json())
        obj.auth = self.auth
        return obj

    def get_automations(
        self,
        filter: str = None,
        limit: int = 100,
        sort: Literal[
            "id",
            "name",
            "runMode",
            "state",
            "createdAt",
            "updatedAt",
            "lastRunAt",
            "lastRunStatus",
            "+id",
            "+name",
            "+runMode",
            "+state",
            "+createdAt",
            "+updatedAt",
            "+lastRunAt",
            "+lastRunStatus",
            "-id",
            "-name",
            "-runMode",
            "-state",
            "-createdAt",
            "-updatedAt",
            "-lastRunAt",
            "-lastRunStatus",
        ] = "id",
    ) -> ListableResource[AutomationListObject]:
        """
        Retrieves a list of automations

        Parameters
        ----------
        filter: str = None
          Allowed filters: name, runMode, lastRunStatus, ownerId
        limit: int = 100
          The number of automations to retrieve.
        sort: Literal["id", "name", "runMode", "state", "createdAt", "updatedAt", "lastRunAt", "lastRunStatus", "+id", "+name", "+runMode", "+state", "+createdAt", "+updatedAt", "+lastRunAt", "+lastRunStatus", "-id", "-name", "-runMode", "-state", "-createdAt", "-updatedAt", "-lastRunAt", "-lastRunStatus"] = "id"
          The field to sort by, with +- prefix indicating sort order. (?query=-name => sort on the name field using descending order)
        """
        query_params = {}
        if filter is not None:
            query_params["filter"] = filter
        if limit is not None:
            query_params["limit"] = limit
        if sort is not None:
            query_params["sort"] = sort
        response = self.auth.rest(
            path="/automations",
            method="GET",
            params=query_params,
            data=None,
        )
        return ListableResource(
            response=response.json(),
            cls=AutomationListObject,
            auth=self.auth,
            path="/automations",
            query_params=query_params,
        )

    def create(
        self, data: AutomationDetailRequestObject
    ) -> AutomationDetailResponseObject:
        """
        Create an automation

        Parameters
        ----------
        data: AutomationDetailRequestObject
          Automation object to create
        """
        if data is not None:
            try:
                data = asdict(data)
            except:
                data = data
        response = self.auth.rest(
            path="/automations",
            method="POST",
            params={},
            data=data,
        )
        obj = AutomationDetailResponseObject(**response.json())
        obj.auth = self.auth
        return obj
