# pylint: disable=too-many-lines,too-many-statements
# coding=utf-8
# --------------------------------------------------------------------------
# Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.9.7, generator: @autorest/python@6.13.7)
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from io import IOBase
import sys
from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload
import urllib.parse

from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import (
    ClientAuthenticationError,
    HttpResponseError,
    ResourceExistsError,
    ResourceNotFoundError,
    ResourceNotModifiedError,
    map_error,
)
from azure.core.pipeline import PipelineResponse
from azure.core.rest import AsyncHttpResponse, HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.tracing.decorator_async import distributed_trace_async
from azure.core.utils import case_insensitive_dict

from ...operations._operations import (
    build_participants_list_request,
    build_participants_update_request,
    build_rooms_create_request,
    build_rooms_delete_request,
    build_rooms_get_request,
    build_rooms_list_request,
    build_rooms_update_request,
)

if sys.version_info >= (3, 9):
    from collections.abc import MutableMapping
else:
    from typing import MutableMapping  # type: ignore  # pylint: disable=ungrouped-imports
JSON = MutableMapping[str, Any]  # pylint: disable=unsubscriptable-object
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]


class RoomsOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.communication.rooms.aio.AzureCommunicationRoomsService`'s
        :attr:`rooms` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @overload
    async def create(self, create_room_request: JSON, *, content_type: str = "application/json", **kwargs: Any) -> JSON:
        # pylint: disable=line-too-long
        """Creates a new room.

        Creates a new room.

        :param create_room_request: The create room request body. Required.
        :type create_room_request: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: JSON object
        :rtype: JSON
        :raises ~azure.core.exceptions.HttpResponseError:

        Example:
            .. code-block:: python

                # JSON input template you can fill out and use as your body input.
                create_room_request = {
                    "participants": {
                        "str": {
                            "role": "str"  # The role of a room participant. The default
                              value is Attendee. Required. Known values are: "Presenter", "Attendee",
                              and "Consumer".
                        }
                    },
                    "pstnDialOutEnabled": bool,  # Optional. Set this flag to true if, at the
                      time of the call, dial out to a PSTN number is enabled in a particular room. By
                      default, this flag is set to false.
                    "validFrom": "2020-02-20 00:00:00",  # Optional. The timestamp from when the
                      room is open for joining. The timestamp is in RFC3339 format:
                      ``yyyy-MM-ddTHH:mm:ssZ``. The default value is the current date time.
                    "validUntil": "2020-02-20 00:00:00"  # Optional. The timestamp from when the
                      room can no longer be joined. The timestamp is in RFC3339 format:
                      ``yyyy-MM-ddTHH:mm:ssZ``. The default value is the current date time plus 180
                      days.
                }

                # response body for status code(s): 201
                response == {
                    "createdAt": "2020-02-20 00:00:00",  # The timestamp when the room was
                      created at the server. The timestamp is in RFC3339 format:
                      ``yyyy-MM-ddTHH:mm:ssZ``. Required.
                    "id": "str",  # Unique identifier of a room. This id is server generated.
                      Required.
                    "pstnDialOutEnabled": bool,  # Set this flag to true if, at the time of the
                      call, dial out to a PSTN number is enabled in a particular room. By default, this
                      flag is set to false. Required.
                    "validFrom": "2020-02-20 00:00:00",  # The timestamp from when the room is
                      open for joining. The timestamp is in RFC3339 format: ``yyyy-MM-ddTHH:mm:ssZ``.
                      Required.
                    "validUntil": "2020-02-20 00:00:00"  # The timestamp from when the room can
                      no longer be joined. The timestamp is in RFC3339 format:
                      ``yyyy-MM-ddTHH:mm:ssZ``. Required.
                }
        """

    @overload
    async def create(
        self, create_room_request: IO[bytes], *, content_type: str = "application/json", **kwargs: Any
    ) -> JSON:
        # pylint: disable=line-too-long
        """Creates a new room.

        Creates a new room.

        :param create_room_request: The create room request body. Required.
        :type create_room_request: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: JSON object
        :rtype: JSON
        :raises ~azure.core.exceptions.HttpResponseError:

        Example:
            .. code-block:: python

                # response body for status code(s): 201
                response == {
                    "createdAt": "2020-02-20 00:00:00",  # The timestamp when the room was
                      created at the server. The timestamp is in RFC3339 format:
                      ``yyyy-MM-ddTHH:mm:ssZ``. Required.
                    "id": "str",  # Unique identifier of a room. This id is server generated.
                      Required.
                    "pstnDialOutEnabled": bool,  # Set this flag to true if, at the time of the
                      call, dial out to a PSTN number is enabled in a particular room. By default, this
                      flag is set to false. Required.
                    "validFrom": "2020-02-20 00:00:00",  # The timestamp from when the room is
                      open for joining. The timestamp is in RFC3339 format: ``yyyy-MM-ddTHH:mm:ssZ``.
                      Required.
                    "validUntil": "2020-02-20 00:00:00"  # The timestamp from when the room can
                      no longer be joined. The timestamp is in RFC3339 format:
                      ``yyyy-MM-ddTHH:mm:ssZ``. Required.
                }
        """

    @distributed_trace_async
    async def create(self, create_room_request: Union[JSON, IO[bytes]], **kwargs: Any) -> JSON:
        # pylint: disable=line-too-long
        """Creates a new room.

        Creates a new room.

        :param create_room_request: The create room request body. Is either a JSON type or a IO[bytes]
         type. Required.
        :type create_room_request: JSON or IO[bytes]
        :return: JSON object
        :rtype: JSON
        :raises ~azure.core.exceptions.HttpResponseError:

        Example:
            .. code-block:: python

                # JSON input template you can fill out and use as your body input.
                create_room_request = {
                    "participants": {
                        "str": {
                            "role": "str"  # The role of a room participant. The default
                              value is Attendee. Required. Known values are: "Presenter", "Attendee",
                              and "Consumer".
                        }
                    },
                    "pstnDialOutEnabled": bool,  # Optional. Set this flag to true if, at the
                      time of the call, dial out to a PSTN number is enabled in a particular room. By
                      default, this flag is set to false.
                    "validFrom": "2020-02-20 00:00:00",  # Optional. The timestamp from when the
                      room is open for joining. The timestamp is in RFC3339 format:
                      ``yyyy-MM-ddTHH:mm:ssZ``. The default value is the current date time.
                    "validUntil": "2020-02-20 00:00:00"  # Optional. The timestamp from when the
                      room can no longer be joined. The timestamp is in RFC3339 format:
                      ``yyyy-MM-ddTHH:mm:ssZ``. The default value is the current date time plus 180
                      days.
                }

                # response body for status code(s): 201
                response == {
                    "createdAt": "2020-02-20 00:00:00",  # The timestamp when the room was
                      created at the server. The timestamp is in RFC3339 format:
                      ``yyyy-MM-ddTHH:mm:ssZ``. Required.
                    "id": "str",  # Unique identifier of a room. This id is server generated.
                      Required.
                    "pstnDialOutEnabled": bool,  # Set this flag to true if, at the time of the
                      call, dial out to a PSTN number is enabled in a particular room. By default, this
                      flag is set to false. Required.
                    "validFrom": "2020-02-20 00:00:00",  # The timestamp from when the room is
                      open for joining. The timestamp is in RFC3339 format: ``yyyy-MM-ddTHH:mm:ssZ``.
                      Required.
                    "validUntil": "2020-02-20 00:00:00"  # The timestamp from when the room can
                      no longer be joined. The timestamp is in RFC3339 format:
                      ``yyyy-MM-ddTHH:mm:ssZ``. Required.
                }
        """
        error_map = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[JSON] = kwargs.pop("cls", None)

        content_type = content_type or "application/json"
        _json = None
        _content = None
        if isinstance(create_room_request, (IOBase, bytes)):
            _content = create_room_request
        else:
            _json = create_room_request

        _request = build_rooms_create_request(
            content_type=content_type,
            api_version=self._config.api_version,
            json=_json,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [201]:
            if _stream:
                await response.read()  # Load the body in memory and close the socket
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            raise HttpResponseError(response=response)

        if response.content:
            deserialized = response.json()
        else:
            deserialized = None

        if cls:
            return cls(pipeline_response, cast(JSON, deserialized), {})  # type: ignore

        return cast(JSON, deserialized)  # type: ignore

    @distributed_trace
    def list(self, **kwargs: Any) -> AsyncIterable[JSON]:
        # pylint: disable=line-too-long
        """Retrieves all created rooms.

        Retrieves all created rooms.

        :return: An iterator like instance of JSON object
        :rtype: ~azure.core.async_paging.AsyncItemPaged[JSON]
        :raises ~azure.core.exceptions.HttpResponseError:

        Example:
            .. code-block:: python

                # response body for status code(s): 200
                response == {
                    "createdAt": "2020-02-20 00:00:00",  # The timestamp when the room was
                      created at the server. The timestamp is in RFC3339 format:
                      ``yyyy-MM-ddTHH:mm:ssZ``. Required.
                    "id": "str",  # Unique identifier of a room. This id is server generated.
                      Required.
                    "pstnDialOutEnabled": bool,  # Set this flag to true if, at the time of the
                      call, dial out to a PSTN number is enabled in a particular room. By default, this
                      flag is set to false. Required.
                    "validFrom": "2020-02-20 00:00:00",  # The timestamp from when the room is
                      open for joining. The timestamp is in RFC3339 format: ``yyyy-MM-ddTHH:mm:ssZ``.
                      Required.
                    "validUntil": "2020-02-20 00:00:00"  # The timestamp from when the room can
                      no longer be joined. The timestamp is in RFC3339 format:
                      ``yyyy-MM-ddTHH:mm:ssZ``. Required.
                }
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[JSON] = kwargs.pop("cls", None)

        error_map = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_rooms_list_request(
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.endpoint", self._config.endpoint, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.endpoint", self._config.endpoint, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = deserialized["value"]
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                if _stream:
                    await response.read()  # Load the body in memory and close the socket
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                raise HttpResponseError(response=response)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace_async
    async def get(self, room_id: str, **kwargs: Any) -> JSON:
        # pylint: disable=line-too-long
        """Retrieves an existing room by id.

        Retrieves an existing room by id.

        :param room_id: The id of the room requested. Required.
        :type room_id: str
        :return: JSON object
        :rtype: JSON
        :raises ~azure.core.exceptions.HttpResponseError:

        Example:
            .. code-block:: python

                # response body for status code(s): 200
                response == {
                    "createdAt": "2020-02-20 00:00:00",  # The timestamp when the room was
                      created at the server. The timestamp is in RFC3339 format:
                      ``yyyy-MM-ddTHH:mm:ssZ``. Required.
                    "id": "str",  # Unique identifier of a room. This id is server generated.
                      Required.
                    "pstnDialOutEnabled": bool,  # Set this flag to true if, at the time of the
                      call, dial out to a PSTN number is enabled in a particular room. By default, this
                      flag is set to false. Required.
                    "validFrom": "2020-02-20 00:00:00",  # The timestamp from when the room is
                      open for joining. The timestamp is in RFC3339 format: ``yyyy-MM-ddTHH:mm:ssZ``.
                      Required.
                    "validUntil": "2020-02-20 00:00:00"  # The timestamp from when the room can
                      no longer be joined. The timestamp is in RFC3339 format:
                      ``yyyy-MM-ddTHH:mm:ssZ``. Required.
                }
        """
        error_map = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[JSON] = kwargs.pop("cls", None)

        _request = build_rooms_get_request(
            room_id=room_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                await response.read()  # Load the body in memory and close the socket
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            raise HttpResponseError(response=response)

        if response.content:
            deserialized = response.json()
        else:
            deserialized = None

        if cls:
            return cls(pipeline_response, cast(JSON, deserialized), {})  # type: ignore

        return cast(JSON, deserialized)  # type: ignore

    @overload
    async def update(
        self,
        room_id: str,
        update_room_request: JSON,
        *,
        content_type: str = "application/merge-patch+json",
        **kwargs: Any
    ) -> JSON:
        # pylint: disable=line-too-long
        """Update a room with given changes.

        Update a room with given changes.

        :param room_id: The id of the room requested. Required.
        :type room_id: str
        :param update_room_request: The update room request. Required.
        :type update_room_request: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/merge-patch+json".
        :paramtype content_type: str
        :return: JSON object
        :rtype: JSON
        :raises ~azure.core.exceptions.HttpResponseError:

        Example:
            .. code-block:: python

                # JSON input template you can fill out and use as your body input.
                update_room_request = {
                    "pstnDialOutEnabled": bool,  # Optional. Set this flag to true if, at the
                      time of the call, dial out to a PSTN number is enabled in a particular room. By
                      default, this flag is set to false.
                    "validFrom": "2020-02-20 00:00:00",  # Optional. (Optional) The timestamp
                      from when the room is open for joining. The timestamp is in RFC3339 format:
                      ``yyyy-MM-ddTHH:mm:ssZ``.
                    "validUntil": "2020-02-20 00:00:00"  # Optional. (Optional) The timestamp
                      from when the room can no longer be joined. The timestamp is in RFC3339 format:
                      ``yyyy-MM-ddTHH:mm:ssZ``.
                }

                # response body for status code(s): 200
                response == {
                    "createdAt": "2020-02-20 00:00:00",  # The timestamp when the room was
                      created at the server. The timestamp is in RFC3339 format:
                      ``yyyy-MM-ddTHH:mm:ssZ``. Required.
                    "id": "str",  # Unique identifier of a room. This id is server generated.
                      Required.
                    "pstnDialOutEnabled": bool,  # Set this flag to true if, at the time of the
                      call, dial out to a PSTN number is enabled in a particular room. By default, this
                      flag is set to false. Required.
                    "validFrom": "2020-02-20 00:00:00",  # The timestamp from when the room is
                      open for joining. The timestamp is in RFC3339 format: ``yyyy-MM-ddTHH:mm:ssZ``.
                      Required.
                    "validUntil": "2020-02-20 00:00:00"  # The timestamp from when the room can
                      no longer be joined. The timestamp is in RFC3339 format:
                      ``yyyy-MM-ddTHH:mm:ssZ``. Required.
                }
        """

    @overload
    async def update(
        self,
        room_id: str,
        update_room_request: IO[bytes],
        *,
        content_type: str = "application/merge-patch+json",
        **kwargs: Any
    ) -> JSON:
        # pylint: disable=line-too-long
        """Update a room with given changes.

        Update a room with given changes.

        :param room_id: The id of the room requested. Required.
        :type room_id: str
        :param update_room_request: The update room request. Required.
        :type update_room_request: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/merge-patch+json".
        :paramtype content_type: str
        :return: JSON object
        :rtype: JSON
        :raises ~azure.core.exceptions.HttpResponseError:

        Example:
            .. code-block:: python

                # response body for status code(s): 200
                response == {
                    "createdAt": "2020-02-20 00:00:00",  # The timestamp when the room was
                      created at the server. The timestamp is in RFC3339 format:
                      ``yyyy-MM-ddTHH:mm:ssZ``. Required.
                    "id": "str",  # Unique identifier of a room. This id is server generated.
                      Required.
                    "pstnDialOutEnabled": bool,  # Set this flag to true if, at the time of the
                      call, dial out to a PSTN number is enabled in a particular room. By default, this
                      flag is set to false. Required.
                    "validFrom": "2020-02-20 00:00:00",  # The timestamp from when the room is
                      open for joining. The timestamp is in RFC3339 format: ``yyyy-MM-ddTHH:mm:ssZ``.
                      Required.
                    "validUntil": "2020-02-20 00:00:00"  # The timestamp from when the room can
                      no longer be joined. The timestamp is in RFC3339 format:
                      ``yyyy-MM-ddTHH:mm:ssZ``. Required.
                }
        """

    @distributed_trace_async
    async def update(self, room_id: str, update_room_request: Union[JSON, IO[bytes]], **kwargs: Any) -> JSON:
        # pylint: disable=line-too-long
        """Update a room with given changes.

        Update a room with given changes.

        :param room_id: The id of the room requested. Required.
        :type room_id: str
        :param update_room_request: The update room request. Is either a JSON type or a IO[bytes] type.
         Required.
        :type update_room_request: JSON or IO[bytes]
        :return: JSON object
        :rtype: JSON
        :raises ~azure.core.exceptions.HttpResponseError:

        Example:
            .. code-block:: python

                # JSON input template you can fill out and use as your body input.
                update_room_request = {
                    "pstnDialOutEnabled": bool,  # Optional. Set this flag to true if, at the
                      time of the call, dial out to a PSTN number is enabled in a particular room. By
                      default, this flag is set to false.
                    "validFrom": "2020-02-20 00:00:00",  # Optional. (Optional) The timestamp
                      from when the room is open for joining. The timestamp is in RFC3339 format:
                      ``yyyy-MM-ddTHH:mm:ssZ``.
                    "validUntil": "2020-02-20 00:00:00"  # Optional. (Optional) The timestamp
                      from when the room can no longer be joined. The timestamp is in RFC3339 format:
                      ``yyyy-MM-ddTHH:mm:ssZ``.
                }

                # response body for status code(s): 200
                response == {
                    "createdAt": "2020-02-20 00:00:00",  # The timestamp when the room was
                      created at the server. The timestamp is in RFC3339 format:
                      ``yyyy-MM-ddTHH:mm:ssZ``. Required.
                    "id": "str",  # Unique identifier of a room. This id is server generated.
                      Required.
                    "pstnDialOutEnabled": bool,  # Set this flag to true if, at the time of the
                      call, dial out to a PSTN number is enabled in a particular room. By default, this
                      flag is set to false. Required.
                    "validFrom": "2020-02-20 00:00:00",  # The timestamp from when the room is
                      open for joining. The timestamp is in RFC3339 format: ``yyyy-MM-ddTHH:mm:ssZ``.
                      Required.
                    "validUntil": "2020-02-20 00:00:00"  # The timestamp from when the room can
                      no longer be joined. The timestamp is in RFC3339 format:
                      ``yyyy-MM-ddTHH:mm:ssZ``. Required.
                }
        """
        error_map = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[JSON] = kwargs.pop("cls", None)

        content_type = content_type or "application/merge-patch+json"
        _json = None
        _content = None
        if isinstance(update_room_request, (IOBase, bytes)):
            _content = update_room_request
        else:
            _json = update_room_request

        _request = build_rooms_update_request(
            room_id=room_id,
            content_type=content_type,
            api_version=self._config.api_version,
            json=_json,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                await response.read()  # Load the body in memory and close the socket
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            raise HttpResponseError(response=response)

        if response.content:
            deserialized = response.json()
        else:
            deserialized = None

        if cls:
            return cls(pipeline_response, cast(JSON, deserialized), {})  # type: ignore

        return cast(JSON, deserialized)  # type: ignore

    @distributed_trace_async
    async def delete(self, room_id: str, **kwargs: Any) -> None:  # pylint: disable=inconsistent-return-statements
        """Delete a room.

        Delete a room.

        :param room_id: The id of the room to be deleted. Required.
        :type room_id: str
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)

        _request = build_rooms_delete_request(
            room_id=room_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [204]:
            if _stream:
                await response.read()  # Load the body in memory and close the socket
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            raise HttpResponseError(response=response)

        if cls:
            return cls(pipeline_response, None, {})  # type: ignore


class ParticipantsOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.communication.rooms.aio.AzureCommunicationRoomsService`'s
        :attr:`participants` attribute.
    """

    def __init__(self, *args, **kwargs) -> None:
        input_args = list(args)
        self._client = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace
    def list(self, room_id: str, **kwargs: Any) -> AsyncIterable[JSON]:
        # pylint: disable=line-too-long
        """Get participants in a room.

        Get participants in a room.

        :param room_id: The id of the room to get participants from. Required.
        :type room_id: str
        :return: An iterator like instance of JSON object
        :rtype: ~azure.core.async_paging.AsyncItemPaged[JSON]
        :raises ~azure.core.exceptions.HttpResponseError:

        Example:
            .. code-block:: python

                # response body for status code(s): 200
                response == {
                    "rawId": "str",  # Raw ID representation of the communication identifier.
                      Please refer to the following document for additional information on Raw ID.
                      :code:`<br>`
                      https://learn.microsoft.com/azure/communication-services/concepts/identifiers?pivots=programming-language-rest#raw-id-representation.
                      Required.
                    "role": "str"  # The role of a room participant. The default value is
                      Attendee. Required. Known values are: "Presenter", "Attendee", and "Consumer".
                }
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[JSON] = kwargs.pop("cls", None)

        error_map = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                _request = build_participants_list_request(
                    room_id=room_id,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.endpoint", self._config.endpoint, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                _request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.endpoint", self._config.endpoint, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = deserialized["value"]
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, AsyncList(list_of_elem)

        async def get_next(next_link=None):
            _request = prepare_request(next_link)

            _stream = False
            pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
                _request, stream=_stream, **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                if _stream:
                    await response.read()  # Load the body in memory and close the socket
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                raise HttpResponseError(response=response)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @overload
    async def update(
        self,
        room_id: str,
        update_participants_request: JSON,
        *,
        content_type: str = "application/merge-patch+json",
        **kwargs: Any
    ) -> JSON:
        # pylint: disable=line-too-long
        """Update participants in a room.

        Update participants in a room.

        :param room_id: The id of the room to update the participants in. Required.
        :type room_id: str
        :param update_participants_request: An updated set of participants of the room. Required.
        :type update_participants_request: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/merge-patch+json".
        :paramtype content_type: str
        :return: JSON
        :rtype: JSON
        :raises ~azure.core.exceptions.HttpResponseError:

        Example:
            .. code-block:: python

                # JSON input template you can fill out and use as your body input.
                update_participants_request = {
                    "participants": {
                        "str": {
                            "role": "str"  # The role of a room participant. The default
                              value is Attendee. Required. Known values are: "Presenter", "Attendee",
                              and "Consumer".
                        }
                    }
                }
        """

    @overload
    async def update(
        self,
        room_id: str,
        update_participants_request: IO[bytes],
        *,
        content_type: str = "application/merge-patch+json",
        **kwargs: Any
    ) -> JSON:
        """Update participants in a room.

        Update participants in a room.

        :param room_id: The id of the room to update the participants in. Required.
        :type room_id: str
        :param update_participants_request: An updated set of participants of the room. Required.
        :type update_participants_request: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/merge-patch+json".
        :paramtype content_type: str
        :return: JSON
        :rtype: JSON
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def update(self, room_id: str, update_participants_request: Union[JSON, IO[bytes]], **kwargs: Any) -> JSON:
        # pylint: disable=line-too-long
        """Update participants in a room.

        Update participants in a room.

        :param room_id: The id of the room to update the participants in. Required.
        :type room_id: str
        :param update_participants_request: An updated set of participants of the room. Is either a
         JSON type or a IO[bytes] type. Required.
        :type update_participants_request: JSON or IO[bytes]
        :return: JSON
        :rtype: JSON
        :raises ~azure.core.exceptions.HttpResponseError:

        Example:
            .. code-block:: python

                # JSON input template you can fill out and use as your body input.
                update_participants_request = {
                    "participants": {
                        "str": {
                            "role": "str"  # The role of a room participant. The default
                              value is Attendee. Required. Known values are: "Presenter", "Attendee",
                              and "Consumer".
                        }
                    }
                }
        """
        error_map = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[JSON] = kwargs.pop("cls", None)

        content_type = content_type or "application/merge-patch+json"
        _json = None
        _content = None
        if isinstance(update_participants_request, (IOBase, bytes)):
            _content = update_participants_request
        else:
            _json = update_participants_request

        _request = build_participants_update_request(
            room_id=room_id,
            content_type=content_type,
            api_version=self._config.api_version,
            json=_json,
            content=_content,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _stream = False
        pipeline_response: PipelineResponse = await self._client._pipeline.run(  # pylint: disable=protected-access
            _request, stream=_stream, **kwargs
        )

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                await response.read()  # Load the body in memory and close the socket
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            raise HttpResponseError(response=response)

        if response.content:
            deserialized = response.json()
        else:
            deserialized = None

        if cls:
            return cls(pipeline_response, cast(JSON, deserialized), {})  # type: ignore

        return cast(JSON, deserialized)  # type: ignore
