# This file was auto-generated by Fern from our API Definition.

from ..core.client_wrapper import SyncClientWrapper
from .raw_client import RawDevicesClient
from .codes.client import CodesClient
import typing
from ..types.sort_order import SortOrder
from ..core.request_options import RequestOptions
from ..core.pagination import SyncPager
from ..types.device import Device
from ..types.list_devices_response import ListDevicesResponse
from ..core.unchecked_base_model import construct_type
from json.decoder import JSONDecodeError
from ..core.api_error import ApiError
from ..types.get_device_response import GetDeviceResponse
from ..core.client_wrapper import AsyncClientWrapper
from .raw_client import AsyncRawDevicesClient
from .codes.client import AsyncCodesClient
from ..core.pagination import AsyncPager


class DevicesClient:
    def __init__(self, *, client_wrapper: SyncClientWrapper):
        self._raw_client = RawDevicesClient(client_wrapper=client_wrapper)
        self.codes = CodesClient(client_wrapper=client_wrapper)

    @property
    def with_raw_response(self) -> RawDevicesClient:
        """
        Retrieves a raw implementation of this client that returns raw responses.

        Returns
        -------
        RawDevicesClient
        """
        return self._raw_client

    def list(
        self,
        *,
        cursor: typing.Optional[str] = None,
        sort_order: typing.Optional[SortOrder] = None,
        limit: typing.Optional[int] = None,
        location_id: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> SyncPager[Device]:
        """
        List devices associated with the merchant. Currently, only Terminal API
        devices are supported.

        Parameters
        ----------
        cursor : typing.Optional[str]
            A pagination cursor returned by a previous call to this endpoint.
            Provide this cursor to retrieve the next set of results for the original query.
            See [Pagination](https://developer.squareup.com/docs/build-basics/common-api-patterns/pagination) for more information.

        sort_order : typing.Optional[SortOrder]
            The order in which results are listed.
            - `ASC` - Oldest to newest.
            - `DESC` - Newest to oldest (default).

        limit : typing.Optional[int]
            The number of results to return in a single page.

        location_id : typing.Optional[str]
            If present, only returns devices at the target location.

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        SyncPager[Device]
            Success

        Examples
        --------
        from square import Square

        client = Square(
            token="YOUR_TOKEN",
        )
        response = client.devices.list()
        for item in response:
            yield item
        # alternatively, you can paginate page-by-page
        for page in response.iter_pages():
            yield page
        """
        _response = self._raw_client._client_wrapper.httpx_client.request(
            "v2/devices",
            method="GET",
            params={
                "cursor": cursor,
                "sort_order": sort_order,
                "limit": limit,
                "location_id": location_id,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _parsed_response = typing.cast(
                    ListDevicesResponse,
                    construct_type(
                        type_=ListDevicesResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                _parsed_next = _parsed_response.cursor
                _has_next = _parsed_next is not None and _parsed_next != ""
                _get_next = lambda: self.list(
                    cursor=_parsed_next,
                    sort_order=sort_order,
                    limit=limit,
                    location_id=location_id,
                    request_options=request_options,
                )
                _items = _parsed_response.devices
                return SyncPager(has_next=_has_next, items=_items, get_next=_get_next)
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    def get(self, device_id: str, *, request_options: typing.Optional[RequestOptions] = None) -> GetDeviceResponse:
        """
        Retrieves Device with the associated `device_id`.

        Parameters
        ----------
        device_id : str
            The unique ID for the desired `Device`.

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        GetDeviceResponse
            Success

        Examples
        --------
        from square import Square

        client = Square(
            token="YOUR_TOKEN",
        )
        client.devices.get(
            device_id="device_id",
        )
        """
        response = self._raw_client.get(device_id, request_options=request_options)
        return response.data


class AsyncDevicesClient:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._raw_client = AsyncRawDevicesClient(client_wrapper=client_wrapper)
        self.codes = AsyncCodesClient(client_wrapper=client_wrapper)

    @property
    def with_raw_response(self) -> AsyncRawDevicesClient:
        """
        Retrieves a raw implementation of this client that returns raw responses.

        Returns
        -------
        AsyncRawDevicesClient
        """
        return self._raw_client

    async def list(
        self,
        *,
        cursor: typing.Optional[str] = None,
        sort_order: typing.Optional[SortOrder] = None,
        limit: typing.Optional[int] = None,
        location_id: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncPager[Device]:
        """
        List devices associated with the merchant. Currently, only Terminal API
        devices are supported.

        Parameters
        ----------
        cursor : typing.Optional[str]
            A pagination cursor returned by a previous call to this endpoint.
            Provide this cursor to retrieve the next set of results for the original query.
            See [Pagination](https://developer.squareup.com/docs/build-basics/common-api-patterns/pagination) for more information.

        sort_order : typing.Optional[SortOrder]
            The order in which results are listed.
            - `ASC` - Oldest to newest.
            - `DESC` - Newest to oldest (default).

        limit : typing.Optional[int]
            The number of results to return in a single page.

        location_id : typing.Optional[str]
            If present, only returns devices at the target location.

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        AsyncPager[Device]
            Success

        Examples
        --------
        import asyncio

        from square import AsyncSquare

        client = AsyncSquare(
            token="YOUR_TOKEN",
        )


        async def main() -> None:
            response = await client.devices.list()
            async for item in response:
                yield item
            # alternatively, you can paginate page-by-page
            async for page in response.iter_pages():
                yield page


        asyncio.run(main())
        """
        _response = await self._raw_client._client_wrapper.httpx_client.request(
            "v2/devices",
            method="GET",
            params={
                "cursor": cursor,
                "sort_order": sort_order,
                "limit": limit,
                "location_id": location_id,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _parsed_response = typing.cast(
                    ListDevicesResponse,
                    construct_type(
                        type_=ListDevicesResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                _parsed_next = _parsed_response.cursor
                _has_next = _parsed_next is not None and _parsed_next != ""
                _get_next = lambda: self.list(
                    cursor=_parsed_next,
                    sort_order=sort_order,
                    limit=limit,
                    location_id=location_id,
                    request_options=request_options,
                )
                _items = _parsed_response.devices
                return AsyncPager(has_next=_has_next, items=_items, get_next=_get_next)
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    async def get(
        self, device_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> GetDeviceResponse:
        """
        Retrieves Device with the associated `device_id`.

        Parameters
        ----------
        device_id : str
            The unique ID for the desired `Device`.

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        GetDeviceResponse
            Success

        Examples
        --------
        import asyncio

        from square import AsyncSquare

        client = AsyncSquare(
            token="YOUR_TOKEN",
        )


        async def main() -> None:
            await client.devices.get(
                device_id="device_id",
            )


        asyncio.run(main())
        """
        response = await self._raw_client.get(device_id, request_options=request_options)
        return response.data
