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

import typing
from ...core.client_wrapper import SyncClientWrapper
from .raw_client import RawCodesClient
from ...types.product_type import ProductType
from ...types.device_code_status import DeviceCodeStatus
from ...core.request_options import RequestOptions
from ...core.pagination import SyncPager
from ...types.device_code import DeviceCode
from ...types.list_device_codes_response import ListDeviceCodesResponse
from ...core.unchecked_base_model import construct_type
from json.decoder import JSONDecodeError
from ...core.api_error import ApiError
from ...requests.device_code import DeviceCodeParams
from ...types.create_device_code_response import CreateDeviceCodeResponse
from ...types.get_device_code_response import GetDeviceCodeResponse
from ...core.client_wrapper import AsyncClientWrapper
from .raw_client import AsyncRawCodesClient
from ...core.pagination import AsyncPager

# this is used as the default value for optional parameters
OMIT = typing.cast(typing.Any, ...)


class CodesClient:
    def __init__(self, *, client_wrapper: SyncClientWrapper):
        self._raw_client = RawCodesClient(client_wrapper=client_wrapper)

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

        Returns
        -------
        RawCodesClient
        """
        return self._raw_client

    def list(
        self,
        *,
        cursor: typing.Optional[str] = None,
        location_id: typing.Optional[str] = None,
        product_type: typing.Optional[ProductType] = None,
        status: typing.Optional[DeviceCodeStatus] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> SyncPager[DeviceCode]:
        """
        Lists all DeviceCodes associated with the merchant.

        Parameters
        ----------
        cursor : typing.Optional[str]
            A pagination cursor returned by a previous call to this endpoint.
            Provide this to retrieve the next set of results for your original query.

            See [Paginating results](https://developer.squareup.com/docs/working-with-apis/pagination) for more information.

        location_id : typing.Optional[str]
            If specified, only returns DeviceCodes of the specified location.
            Returns DeviceCodes of all locations if empty.

        product_type : typing.Optional[ProductType]
            If specified, only returns DeviceCodes targeting the specified product type.
            Returns DeviceCodes of all product types if empty.

        status : typing.Optional[DeviceCodeStatus]
            If specified, returns DeviceCodes with the specified statuses.
            Returns DeviceCodes of status `PAIRED` and `UNPAIRED` if empty.

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

        Returns
        -------
        SyncPager[DeviceCode]
            Success

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

        client = Square(
            token="YOUR_TOKEN",
        )
        response = client.devices.codes.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/codes",
            method="GET",
            params={
                "cursor": cursor,
                "location_id": location_id,
                "product_type": product_type,
                "status": status,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _parsed_response = typing.cast(
                    ListDeviceCodesResponse,
                    construct_type(
                        type_=ListDeviceCodesResponse,  # 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,
                    location_id=location_id,
                    product_type=product_type,
                    status=status,
                    request_options=request_options,
                )
                _items = _parsed_response.device_codes
                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 create(
        self,
        *,
        idempotency_key: str,
        device_code: DeviceCodeParams,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> CreateDeviceCodeResponse:
        """
        Creates a DeviceCode that can be used to login to a Square Terminal device to enter the connected
        terminal mode.

        Parameters
        ----------
        idempotency_key : str
            A unique string that identifies this CreateDeviceCode request. Keys can
            be any valid string but must be unique for every CreateDeviceCode request.

            See [Idempotency keys](https://developer.squareup.com/docs/build-basics/common-api-patterns/idempotency) for more information.

        device_code : DeviceCodeParams
            The device code to create.

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

        Returns
        -------
        CreateDeviceCodeResponse
            Success

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

        client = Square(
            token="YOUR_TOKEN",
        )
        client.devices.codes.create(
            idempotency_key="01bb00a6-0c86-4770-94ed-f5fca973cd56",
            device_code={
                "name": "Counter 1",
                "product_type": "TERMINAL_API",
                "location_id": "B5E4484SHHNYH",
            },
        )
        """
        response = self._raw_client.create(
            idempotency_key=idempotency_key, device_code=device_code, request_options=request_options
        )
        return response.data

    def get(self, id: str, *, request_options: typing.Optional[RequestOptions] = None) -> GetDeviceCodeResponse:
        """
        Retrieves DeviceCode with the associated ID.

        Parameters
        ----------
        id : str
            The unique identifier for the device code.

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

        Returns
        -------
        GetDeviceCodeResponse
            Success

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

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


class AsyncCodesClient:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._raw_client = AsyncRawCodesClient(client_wrapper=client_wrapper)

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

        Returns
        -------
        AsyncRawCodesClient
        """
        return self._raw_client

    async def list(
        self,
        *,
        cursor: typing.Optional[str] = None,
        location_id: typing.Optional[str] = None,
        product_type: typing.Optional[ProductType] = None,
        status: typing.Optional[DeviceCodeStatus] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncPager[DeviceCode]:
        """
        Lists all DeviceCodes associated with the merchant.

        Parameters
        ----------
        cursor : typing.Optional[str]
            A pagination cursor returned by a previous call to this endpoint.
            Provide this to retrieve the next set of results for your original query.

            See [Paginating results](https://developer.squareup.com/docs/working-with-apis/pagination) for more information.

        location_id : typing.Optional[str]
            If specified, only returns DeviceCodes of the specified location.
            Returns DeviceCodes of all locations if empty.

        product_type : typing.Optional[ProductType]
            If specified, only returns DeviceCodes targeting the specified product type.
            Returns DeviceCodes of all product types if empty.

        status : typing.Optional[DeviceCodeStatus]
            If specified, returns DeviceCodes with the specified statuses.
            Returns DeviceCodes of status `PAIRED` and `UNPAIRED` if empty.

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

        Returns
        -------
        AsyncPager[DeviceCode]
            Success

        Examples
        --------
        import asyncio

        from square import AsyncSquare

        client = AsyncSquare(
            token="YOUR_TOKEN",
        )


        async def main() -> None:
            response = await client.devices.codes.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/codes",
            method="GET",
            params={
                "cursor": cursor,
                "location_id": location_id,
                "product_type": product_type,
                "status": status,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _parsed_response = typing.cast(
                    ListDeviceCodesResponse,
                    construct_type(
                        type_=ListDeviceCodesResponse,  # 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,
                    location_id=location_id,
                    product_type=product_type,
                    status=status,
                    request_options=request_options,
                )
                _items = _parsed_response.device_codes
                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 create(
        self,
        *,
        idempotency_key: str,
        device_code: DeviceCodeParams,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> CreateDeviceCodeResponse:
        """
        Creates a DeviceCode that can be used to login to a Square Terminal device to enter the connected
        terminal mode.

        Parameters
        ----------
        idempotency_key : str
            A unique string that identifies this CreateDeviceCode request. Keys can
            be any valid string but must be unique for every CreateDeviceCode request.

            See [Idempotency keys](https://developer.squareup.com/docs/build-basics/common-api-patterns/idempotency) for more information.

        device_code : DeviceCodeParams
            The device code to create.

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

        Returns
        -------
        CreateDeviceCodeResponse
            Success

        Examples
        --------
        import asyncio

        from square import AsyncSquare

        client = AsyncSquare(
            token="YOUR_TOKEN",
        )


        async def main() -> None:
            await client.devices.codes.create(
                idempotency_key="01bb00a6-0c86-4770-94ed-f5fca973cd56",
                device_code={
                    "name": "Counter 1",
                    "product_type": "TERMINAL_API",
                    "location_id": "B5E4484SHHNYH",
                },
            )


        asyncio.run(main())
        """
        response = await self._raw_client.create(
            idempotency_key=idempotency_key, device_code=device_code, request_options=request_options
        )
        return response.data

    async def get(self, id: str, *, request_options: typing.Optional[RequestOptions] = None) -> GetDeviceCodeResponse:
        """
        Retrieves DeviceCode with the associated ID.

        Parameters
        ----------
        id : str
            The unique identifier for the device code.

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

        Returns
        -------
        GetDeviceCodeResponse
            Success

        Examples
        --------
        import asyncio

        from square import AsyncSquare

        client = AsyncSquare(
            token="YOUR_TOKEN",
        )


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


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