r"""
    This code was generated by
   ___ _ _ _ _ _    _ ____    ____ ____ _    ____ ____ _  _ ____ ____ ____ ___ __   __
    |  | | | | |    | |  | __ |  | |__| | __ | __ |___ |\ | |___ |__/ |__|  | |  | |__/
    |  |_|_| | |___ | |__|    |__| |  | |    |__] |___ | \| |___ |  \ |  |  | |__| |  \

    Twilio - Microvisor
    This is the public Twilio REST API.

    NOTE: This class is auto generated by OpenAPI Generator.
    https://openapi-generator.tech
    Do not edit the class manually.
"""


from datetime import datetime
from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator
from twilio.base import deserialize, values
from twilio.base.instance_context import InstanceContext
from twilio.base.instance_resource import InstanceResource
from twilio.base.list_resource import ListResource
from twilio.base.version import Version
from twilio.base.page import Page
from twilio.rest.microvisor.v1.device.device_config import DeviceConfigList
from twilio.rest.microvisor.v1.device.device_secret import DeviceSecretList


class DeviceInstance(InstanceResource):

    """
    :ivar sid: A 34-character string that uniquely identifies this Device.
    :ivar unique_name: A developer-defined string that uniquely identifies the Device. This value must be unique for all Devices on this Account. The `unique_name` value may be used as an alternative to the `sid` in the URL path to address the resource.
    :ivar account_sid: The unique SID identifier of the Account.
    :ivar app: Information about the target App and the App reported by this Device. Contains the properties `target_sid`, `date_targeted`, `update_status` (one of `up-to-date`, `pending` and `error`), `update_error_code`, `reported_sid` and `date_reported`.
    :ivar logging: Object specifying whether application logging is enabled for this Device. Contains the properties `enabled` and `date_expires`.
    :ivar date_created: The date that this Device was created, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format.
    :ivar date_updated: The date that this Device was last updated, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format.
    :ivar url: The URL of this resource.
    :ivar links: The absolute URLs of related resources.
    """

    def __init__(
        self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None
    ):
        super().__init__(version)

        self.sid: Optional[str] = payload.get("sid")
        self.unique_name: Optional[str] = payload.get("unique_name")
        self.account_sid: Optional[str] = payload.get("account_sid")
        self.app: Optional[Dict[str, object]] = payload.get("app")
        self.logging: Optional[Dict[str, object]] = payload.get("logging")
        self.date_created: Optional[datetime] = deserialize.iso8601_datetime(
            payload.get("date_created")
        )
        self.date_updated: Optional[datetime] = deserialize.iso8601_datetime(
            payload.get("date_updated")
        )
        self.url: Optional[str] = payload.get("url")
        self.links: Optional[Dict[str, object]] = payload.get("links")

        self._solution = {
            "sid": sid or self.sid,
        }
        self._context: Optional[DeviceContext] = None

    @property
    def _proxy(self) -> "DeviceContext":
        """
        Generate an instance context for the instance, the context is capable of
        performing various actions. All instance actions are proxied to the context

        :returns: DeviceContext for this DeviceInstance
        """
        if self._context is None:
            self._context = DeviceContext(
                self._version,
                sid=self._solution["sid"],
            )
        return self._context

    def fetch(self) -> "DeviceInstance":
        """
        Fetch the DeviceInstance


        :returns: The fetched DeviceInstance
        """
        return self._proxy.fetch()

    async def fetch_async(self) -> "DeviceInstance":
        """
        Asynchronous coroutine to fetch the DeviceInstance


        :returns: The fetched DeviceInstance
        """
        return await self._proxy.fetch_async()

    def update(
        self,
        unique_name: Union[str, object] = values.unset,
        target_app: Union[str, object] = values.unset,
        logging_enabled: Union[bool, object] = values.unset,
        restart_app: Union[bool, object] = values.unset,
    ) -> "DeviceInstance":
        """
        Update the DeviceInstance

        :param unique_name: A unique and addressable name to be assigned to this Device by the developer. It may be used in place of the Device SID.
        :param target_app: The SID or unique name of the App to be targeted to the Device.
        :param logging_enabled: A Boolean flag specifying whether to enable application logging. Logs will be enabled or extended for 24 hours.
        :param restart_app: Set to true to restart the App running on the Device.

        :returns: The updated DeviceInstance
        """
        return self._proxy.update(
            unique_name=unique_name,
            target_app=target_app,
            logging_enabled=logging_enabled,
            restart_app=restart_app,
        )

    async def update_async(
        self,
        unique_name: Union[str, object] = values.unset,
        target_app: Union[str, object] = values.unset,
        logging_enabled: Union[bool, object] = values.unset,
        restart_app: Union[bool, object] = values.unset,
    ) -> "DeviceInstance":
        """
        Asynchronous coroutine to update the DeviceInstance

        :param unique_name: A unique and addressable name to be assigned to this Device by the developer. It may be used in place of the Device SID.
        :param target_app: The SID or unique name of the App to be targeted to the Device.
        :param logging_enabled: A Boolean flag specifying whether to enable application logging. Logs will be enabled or extended for 24 hours.
        :param restart_app: Set to true to restart the App running on the Device.

        :returns: The updated DeviceInstance
        """
        return await self._proxy.update_async(
            unique_name=unique_name,
            target_app=target_app,
            logging_enabled=logging_enabled,
            restart_app=restart_app,
        )

    @property
    def device_configs(self) -> DeviceConfigList:
        """
        Access the device_configs
        """
        return self._proxy.device_configs

    @property
    def device_secrets(self) -> DeviceSecretList:
        """
        Access the device_secrets
        """
        return self._proxy.device_secrets

    def __repr__(self) -> str:
        """
        Provide a friendly representation

        :returns: Machine friendly representation
        """
        context = " ".join("{}={}".format(k, v) for k, v in self._solution.items())
        return "<Twilio.Microvisor.V1.DeviceInstance {}>".format(context)


class DeviceContext(InstanceContext):
    def __init__(self, version: Version, sid: str):
        """
        Initialize the DeviceContext

        :param version: Version that contains the resource
        :param sid: A 34-character string that uniquely identifies this Device.
        """
        super().__init__(version)

        # Path Solution
        self._solution = {
            "sid": sid,
        }
        self._uri = "/Devices/{sid}".format(**self._solution)

        self._device_configs: Optional[DeviceConfigList] = None
        self._device_secrets: Optional[DeviceSecretList] = None

    def fetch(self) -> DeviceInstance:
        """
        Fetch the DeviceInstance


        :returns: The fetched DeviceInstance
        """

        payload = self._version.fetch(
            method="GET",
            uri=self._uri,
        )

        return DeviceInstance(
            self._version,
            payload,
            sid=self._solution["sid"],
        )

    async def fetch_async(self) -> DeviceInstance:
        """
        Asynchronous coroutine to fetch the DeviceInstance


        :returns: The fetched DeviceInstance
        """

        payload = await self._version.fetch_async(
            method="GET",
            uri=self._uri,
        )

        return DeviceInstance(
            self._version,
            payload,
            sid=self._solution["sid"],
        )

    def update(
        self,
        unique_name: Union[str, object] = values.unset,
        target_app: Union[str, object] = values.unset,
        logging_enabled: Union[bool, object] = values.unset,
        restart_app: Union[bool, object] = values.unset,
    ) -> DeviceInstance:
        """
        Update the DeviceInstance

        :param unique_name: A unique and addressable name to be assigned to this Device by the developer. It may be used in place of the Device SID.
        :param target_app: The SID or unique name of the App to be targeted to the Device.
        :param logging_enabled: A Boolean flag specifying whether to enable application logging. Logs will be enabled or extended for 24 hours.
        :param restart_app: Set to true to restart the App running on the Device.

        :returns: The updated DeviceInstance
        """
        data = values.of(
            {
                "UniqueName": unique_name,
                "TargetApp": target_app,
                "LoggingEnabled": logging_enabled,
                "RestartApp": restart_app,
            }
        )

        payload = self._version.update(
            method="POST",
            uri=self._uri,
            data=data,
        )

        return DeviceInstance(self._version, payload, sid=self._solution["sid"])

    async def update_async(
        self,
        unique_name: Union[str, object] = values.unset,
        target_app: Union[str, object] = values.unset,
        logging_enabled: Union[bool, object] = values.unset,
        restart_app: Union[bool, object] = values.unset,
    ) -> DeviceInstance:
        """
        Asynchronous coroutine to update the DeviceInstance

        :param unique_name: A unique and addressable name to be assigned to this Device by the developer. It may be used in place of the Device SID.
        :param target_app: The SID or unique name of the App to be targeted to the Device.
        :param logging_enabled: A Boolean flag specifying whether to enable application logging. Logs will be enabled or extended for 24 hours.
        :param restart_app: Set to true to restart the App running on the Device.

        :returns: The updated DeviceInstance
        """
        data = values.of(
            {
                "UniqueName": unique_name,
                "TargetApp": target_app,
                "LoggingEnabled": logging_enabled,
                "RestartApp": restart_app,
            }
        )

        payload = await self._version.update_async(
            method="POST",
            uri=self._uri,
            data=data,
        )

        return DeviceInstance(self._version, payload, sid=self._solution["sid"])

    @property
    def device_configs(self) -> DeviceConfigList:
        """
        Access the device_configs
        """
        if self._device_configs is None:
            self._device_configs = DeviceConfigList(
                self._version,
                self._solution["sid"],
            )
        return self._device_configs

    @property
    def device_secrets(self) -> DeviceSecretList:
        """
        Access the device_secrets
        """
        if self._device_secrets is None:
            self._device_secrets = DeviceSecretList(
                self._version,
                self._solution["sid"],
            )
        return self._device_secrets

    def __repr__(self) -> str:
        """
        Provide a friendly representation

        :returns: Machine friendly representation
        """
        context = " ".join("{}={}".format(k, v) for k, v in self._solution.items())
        return "<Twilio.Microvisor.V1.DeviceContext {}>".format(context)


class DevicePage(Page):
    def get_instance(self, payload: Dict[str, Any]) -> DeviceInstance:
        """
        Build an instance of DeviceInstance

        :param payload: Payload response from the API
        """
        return DeviceInstance(self._version, payload)

    def __repr__(self) -> str:
        """
        Provide a friendly representation

        :returns: Machine friendly representation
        """
        return "<Twilio.Microvisor.V1.DevicePage>"


class DeviceList(ListResource):
    def __init__(self, version: Version):
        """
        Initialize the DeviceList

        :param version: Version that contains the resource

        """
        super().__init__(version)

        self._uri = "/Devices"

    def stream(
        self,
        limit: Optional[int] = None,
        page_size: Optional[int] = None,
    ) -> Iterator[DeviceInstance]:
        """
        Streams DeviceInstance records from the API as a generator stream.
        This operation lazily loads records as efficiently as possible until the limit
        is reached.
        The results are returned as a generator, so this operation is memory efficient.

        :param limit: Upper limit for the number of records to return. stream()
                      guarantees to never return more than limit.  Default is no limit
        :param page_size: Number of records to fetch per request, when not set will use
                          the default value of 50 records.  If no page_size is defined
                          but a limit is defined, stream() will attempt to read the
                          limit with the most efficient page size, i.e. min(limit, 1000)

        :returns: Generator that will yield up to limit results
        """
        limits = self._version.read_limits(limit, page_size)
        page = self.page(page_size=limits["page_size"])

        return self._version.stream(page, limits["limit"])

    async def stream_async(
        self,
        limit: Optional[int] = None,
        page_size: Optional[int] = None,
    ) -> AsyncIterator[DeviceInstance]:
        """
        Asynchronously streams DeviceInstance records from the API as a generator stream.
        This operation lazily loads records as efficiently as possible until the limit
        is reached.
        The results are returned as a generator, so this operation is memory efficient.

        :param limit: Upper limit for the number of records to return. stream()
                      guarantees to never return more than limit.  Default is no limit
        :param page_size: Number of records to fetch per request, when not set will use
                          the default value of 50 records.  If no page_size is defined
                          but a limit is defined, stream() will attempt to read the
                          limit with the most efficient page size, i.e. min(limit, 1000)

        :returns: Generator that will yield up to limit results
        """
        limits = self._version.read_limits(limit, page_size)
        page = await self.page_async(page_size=limits["page_size"])

        return self._version.stream_async(page, limits["limit"])

    def list(
        self,
        limit: Optional[int] = None,
        page_size: Optional[int] = None,
    ) -> List[DeviceInstance]:
        """
        Lists DeviceInstance records from the API as a list.
        Unlike stream(), this operation is eager and will load `limit` records into
        memory before returning.

        :param limit: Upper limit for the number of records to return. list() guarantees
                      never to return more than limit.  Default is no limit
        :param page_size: Number of records to fetch per request, when not set will use
                          the default value of 50 records.  If no page_size is defined
                          but a limit is defined, list() will attempt to read the limit
                          with the most efficient page size, i.e. min(limit, 1000)

        :returns: list that will contain up to limit results
        """
        return list(
            self.stream(
                limit=limit,
                page_size=page_size,
            )
        )

    async def list_async(
        self,
        limit: Optional[int] = None,
        page_size: Optional[int] = None,
    ) -> List[DeviceInstance]:
        """
        Asynchronously lists DeviceInstance records from the API as a list.
        Unlike stream(), this operation is eager and will load `limit` records into
        memory before returning.

        :param limit: Upper limit for the number of records to return. list() guarantees
                      never to return more than limit.  Default is no limit
        :param page_size: Number of records to fetch per request, when not set will use
                          the default value of 50 records.  If no page_size is defined
                          but a limit is defined, list() will attempt to read the limit
                          with the most efficient page size, i.e. min(limit, 1000)

        :returns: list that will contain up to limit results
        """
        return [
            record
            async for record in await self.stream_async(
                limit=limit,
                page_size=page_size,
            )
        ]

    def page(
        self,
        page_token: Union[str, object] = values.unset,
        page_number: Union[int, object] = values.unset,
        page_size: Union[int, object] = values.unset,
    ) -> DevicePage:
        """
        Retrieve a single page of DeviceInstance records from the API.
        Request is executed immediately

        :param page_token: PageToken provided by the API
        :param page_number: Page Number, this value is simply for client state
        :param page_size: Number of records to return, defaults to 50

        :returns: Page of DeviceInstance
        """
        data = values.of(
            {
                "PageToken": page_token,
                "Page": page_number,
                "PageSize": page_size,
            }
        )

        response = self._version.page(method="GET", uri=self._uri, params=data)
        return DevicePage(self._version, response)

    async def page_async(
        self,
        page_token: Union[str, object] = values.unset,
        page_number: Union[int, object] = values.unset,
        page_size: Union[int, object] = values.unset,
    ) -> DevicePage:
        """
        Asynchronously retrieve a single page of DeviceInstance records from the API.
        Request is executed immediately

        :param page_token: PageToken provided by the API
        :param page_number: Page Number, this value is simply for client state
        :param page_size: Number of records to return, defaults to 50

        :returns: Page of DeviceInstance
        """
        data = values.of(
            {
                "PageToken": page_token,
                "Page": page_number,
                "PageSize": page_size,
            }
        )

        response = await self._version.page_async(
            method="GET", uri=self._uri, params=data
        )
        return DevicePage(self._version, response)

    def get_page(self, target_url: str) -> DevicePage:
        """
        Retrieve a specific page of DeviceInstance records from the API.
        Request is executed immediately

        :param target_url: API-generated URL for the requested results page

        :returns: Page of DeviceInstance
        """
        response = self._version.domain.twilio.request("GET", target_url)
        return DevicePage(self._version, response)

    async def get_page_async(self, target_url: str) -> DevicePage:
        """
        Asynchronously retrieve a specific page of DeviceInstance records from the API.
        Request is executed immediately

        :param target_url: API-generated URL for the requested results page

        :returns: Page of DeviceInstance
        """
        response = await self._version.domain.twilio.request_async("GET", target_url)
        return DevicePage(self._version, response)

    def get(self, sid: str) -> DeviceContext:
        """
        Constructs a DeviceContext

        :param sid: A 34-character string that uniquely identifies this Device.
        """
        return DeviceContext(self._version, sid=sid)

    def __call__(self, sid: str) -> DeviceContext:
        """
        Constructs a DeviceContext

        :param sid: A 34-character string that uniquely identifies this Device.
        """
        return DeviceContext(self._version, sid=sid)

    def __repr__(self) -> str:
        """
        Provide a friendly representation

        :returns: Machine friendly representation
        """
        return "<Twilio.Microvisor.V1.DeviceList>"
