# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
import datetime
from typing import TYPE_CHECKING
import warnings

from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpRequest, HttpResponse

from .. import models

if TYPE_CHECKING:
    # pylint: disable=unused-import,ungrouped-imports
    from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar

    T = TypeVar('T')
    ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]

class AzureCommunicationChatServiceOperationsMixin(object):

    def list_chat_read_receipts(
        self,
        chat_thread_id,  # type: str
        **kwargs  # type: Any
    ):
        # type: (...) -> Iterable["models.ReadReceiptsCollection"]
        """Gets read receipts for a thread.

        Gets read receipts for a thread.

        :param chat_thread_id: Thread id to get the read receipts for.
        :type chat_thread_id: str
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: An iterator like instance of either ReadReceiptsCollection or the result of cls(response)
        :rtype: ~azure.core.paging.ItemPaged[~azure.communication.chat.models.ReadReceiptsCollection]
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        cls = kwargs.pop('cls', None)  # type: ClsType["models.ReadReceiptsCollection"]
        error_map = {
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            401: lambda response: ClientAuthenticationError(response=response, model=self._deserialize(models.Error, response)),
            403: lambda response: HttpResponseError(response=response, model=self._deserialize(models.Error, response)),
            429: lambda response: HttpResponseError(response=response, model=self._deserialize(models.Error, response)),
            503: lambda response: HttpResponseError(response=response, model=self._deserialize(models.Error, response)),
        }
        error_map.update(kwargs.pop('error_map', {}))
        api_version = "2020-09-21-preview2"
        accept = "application/json"

        def prepare_request(next_link=None):
            # Construct headers
            header_parameters = {}  # type: Dict[str, Any]
            header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')

            if not next_link:
                # Construct URL
                url = self.list_chat_read_receipts.metadata['url']  # type: ignore
                path_format_arguments = {
                    'endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
                    'chatThreadId': self._serialize.url("chat_thread_id", chat_thread_id, 'str'),
                }
                url = self._client.format_url(url, **path_format_arguments)
                # Construct parameters
                query_parameters = {}  # type: Dict[str, Any]
                query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')

                request = self._client.get(url, query_parameters, header_parameters)
            else:
                url = next_link
                query_parameters = {}  # type: Dict[str, Any]
                path_format_arguments = {
                    'endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
                    'chatThreadId': self._serialize.url("chat_thread_id", chat_thread_id, 'str'),
                }
                url = self._client.format_url(url, **path_format_arguments)
                request = self._client.get(url, query_parameters, header_parameters)
            return request

        def extract_data(pipeline_response):
            deserialized = self._deserialize('ReadReceiptsCollection', pipeline_response)
            list_of_elem = deserialized.value
            if cls:
                list_of_elem = cls(list_of_elem)
            return deserialized.next_link or None, iter(list_of_elem)

        def get_next(next_link=None):
            request = prepare_request(next_link)

            pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                raise HttpResponseError(response=response)

            return pipeline_response

        return ItemPaged(
            get_next, extract_data
        )
    list_chat_read_receipts.metadata = {'url': '/chat/threads/{chatThreadId}/readreceipts'}  # type: ignore

    def send_chat_read_receipt(
        self,
        chat_thread_id,  # type: str
        body,  # type: "models.SendReadReceiptRequest"
        **kwargs  # type: Any
    ):
        # type: (...) -> None
        """Sends a read receipt event to a thread, on behalf of a user.

        Sends a read receipt event to a thread, on behalf of a user.

        :param chat_thread_id: Thread id to send the read receipt event to.
        :type chat_thread_id: str
        :param body: Read receipt details.
        :type body: ~azure.communication.chat.models.SendReadReceiptRequest
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: None, or the result of cls(response)
        :rtype: None
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        cls = kwargs.pop('cls', None)  # type: ClsType[None]
        error_map = {
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            401: lambda response: ClientAuthenticationError(response=response, model=self._deserialize(models.Error, response)),
            403: lambda response: HttpResponseError(response=response, model=self._deserialize(models.Error, response)),
            429: lambda response: HttpResponseError(response=response, model=self._deserialize(models.Error, response)),
            503: lambda response: HttpResponseError(response=response, model=self._deserialize(models.Error, response)),
        }
        error_map.update(kwargs.pop('error_map', {}))
        api_version = "2020-09-21-preview2"
        content_type = kwargs.pop("content_type", "application/json")
        accept = "application/json"

        # Construct URL
        url = self.send_chat_read_receipt.metadata['url']  # type: ignore
        path_format_arguments = {
            'endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
            'chatThreadId': self._serialize.url("chat_thread_id", chat_thread_id, 'str'),
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}  # type: Dict[str, Any]
        query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')

        # Construct headers
        header_parameters = {}  # type: Dict[str, Any]
        header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')
        header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')

        body_content_kwargs = {}  # type: Dict[str, Any]
        body_content = self._serialize.body(body, 'SendReadReceiptRequest')
        body_content_kwargs['content'] = body_content
        request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs)
        pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
        response = pipeline_response.http_response

        if response.status_code not in [201]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            raise HttpResponseError(response=response)

        if cls:
            return cls(pipeline_response, None, {})

    send_chat_read_receipt.metadata = {'url': '/chat/threads/{chatThreadId}/readreceipts'}  # type: ignore

    def send_chat_message(
        self,
        chat_thread_id,  # type: str
        body,  # type: "models.SendChatMessageRequest"
        **kwargs  # type: Any
    ):
        # type: (...) -> "models.SendChatMessageResult"
        """Sends a message to a thread.

        Sends a message to a thread.

        :param chat_thread_id: The thread id to send the message to.
        :type chat_thread_id: str
        :param body: Details of the message to send.
        :type body: ~azure.communication.chat.models.SendChatMessageRequest
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: SendChatMessageResult, or the result of cls(response)
        :rtype: ~azure.communication.chat.models.SendChatMessageResult
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        cls = kwargs.pop('cls', None)  # type: ClsType["models.SendChatMessageResult"]
        error_map = {
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            401: lambda response: ClientAuthenticationError(response=response, model=self._deserialize(models.Error, response)),
            403: lambda response: HttpResponseError(response=response, model=self._deserialize(models.Error, response)),
            429: lambda response: HttpResponseError(response=response, model=self._deserialize(models.Error, response)),
            503: lambda response: HttpResponseError(response=response, model=self._deserialize(models.Error, response)),
        }
        error_map.update(kwargs.pop('error_map', {}))
        api_version = "2020-09-21-preview2"
        content_type = kwargs.pop("content_type", "application/json")
        accept = "application/json"

        # Construct URL
        url = self.send_chat_message.metadata['url']  # type: ignore
        path_format_arguments = {
            'endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
            'chatThreadId': self._serialize.url("chat_thread_id", chat_thread_id, 'str'),
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}  # type: Dict[str, Any]
        query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')

        # Construct headers
        header_parameters = {}  # type: Dict[str, Any]
        header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')
        header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')

        body_content_kwargs = {}  # type: Dict[str, Any]
        body_content = self._serialize.body(body, 'SendChatMessageRequest')
        body_content_kwargs['content'] = body_content
        request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs)
        pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
        response = pipeline_response.http_response

        if response.status_code not in [201]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            raise HttpResponseError(response=response)

        deserialized = self._deserialize('SendChatMessageResult', pipeline_response)

        if cls:
            return cls(pipeline_response, deserialized, {})

        return deserialized
    send_chat_message.metadata = {'url': '/chat/threads/{chatThreadId}/messages'}  # type: ignore

    def list_chat_messages(
        self,
        chat_thread_id,  # type: str
        max_page_size=None,  # type: Optional[int]
        start_time=None,  # type: Optional[datetime.datetime]
        **kwargs  # type: Any
    ):
        # type: (...) -> Iterable["models.ChatMessagesCollection"]
        """Gets a list of messages from a thread.

        Gets a list of messages from a thread.

        :param chat_thread_id: The thread id of the message.
        :type chat_thread_id: str
        :param max_page_size: The maximum number of messages to be returned per page.
        :type max_page_size: int
        :param start_time: The earliest point in time to get messages up to. The timestamp should be in
         ISO8601 format: ``yyyy-MM-ddTHH:mm:ssZ``.
        :type start_time: ~datetime.datetime
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: An iterator like instance of either ChatMessagesCollection or the result of cls(response)
        :rtype: ~azure.core.paging.ItemPaged[~azure.communication.chat.models.ChatMessagesCollection]
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        cls = kwargs.pop('cls', None)  # type: ClsType["models.ChatMessagesCollection"]
        error_map = {
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            401: lambda response: ClientAuthenticationError(response=response, model=self._deserialize(models.Error, response)),
            403: lambda response: HttpResponseError(response=response, model=self._deserialize(models.Error, response)),
            429: lambda response: HttpResponseError(response=response, model=self._deserialize(models.Error, response)),
            503: lambda response: HttpResponseError(response=response, model=self._deserialize(models.Error, response)),
        }
        error_map.update(kwargs.pop('error_map', {}))
        api_version = "2020-09-21-preview2"
        accept = "application/json"

        def prepare_request(next_link=None):
            # Construct headers
            header_parameters = {}  # type: Dict[str, Any]
            header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')

            if not next_link:
                # Construct URL
                url = self.list_chat_messages.metadata['url']  # type: ignore
                path_format_arguments = {
                    'endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
                    'chatThreadId': self._serialize.url("chat_thread_id", chat_thread_id, 'str'),
                }
                url = self._client.format_url(url, **path_format_arguments)
                # Construct parameters
                query_parameters = {}  # type: Dict[str, Any]
                if max_page_size is not None:
                    query_parameters['maxPageSize'] = self._serialize.query("max_page_size", max_page_size, 'int')
                if start_time is not None:
                    query_parameters['startTime'] = self._serialize.query("start_time", start_time, 'iso-8601')
                query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')

                request = self._client.get(url, query_parameters, header_parameters)
            else:
                url = next_link
                query_parameters = {}  # type: Dict[str, Any]
                path_format_arguments = {
                    'endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
                    'chatThreadId': self._serialize.url("chat_thread_id", chat_thread_id, 'str'),
                }
                url = self._client.format_url(url, **path_format_arguments)
                request = self._client.get(url, query_parameters, header_parameters)
            return request

        def extract_data(pipeline_response):
            deserialized = self._deserialize('ChatMessagesCollection', pipeline_response)
            list_of_elem = deserialized.value
            if cls:
                list_of_elem = cls(list_of_elem)
            return deserialized.next_link or None, iter(list_of_elem)

        def get_next(next_link=None):
            request = prepare_request(next_link)

            pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                raise HttpResponseError(response=response)

            return pipeline_response

        return ItemPaged(
            get_next, extract_data
        )
    list_chat_messages.metadata = {'url': '/chat/threads/{chatThreadId}/messages'}  # type: ignore

    def get_chat_message(
        self,
        chat_thread_id,  # type: str
        chat_message_id,  # type: str
        **kwargs  # type: Any
    ):
        # type: (...) -> "models.ChatMessage"
        """Gets a message by id.

        Gets a message by id.

        :param chat_thread_id: The thread id to which the message was sent.
        :type chat_thread_id: str
        :param chat_message_id: The message id.
        :type chat_message_id: str
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: ChatMessage, or the result of cls(response)
        :rtype: ~azure.communication.chat.models.ChatMessage
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        cls = kwargs.pop('cls', None)  # type: ClsType["models.ChatMessage"]
        error_map = {
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            401: lambda response: ClientAuthenticationError(response=response, model=self._deserialize(models.Error, response)),
            403: lambda response: HttpResponseError(response=response, model=self._deserialize(models.Error, response)),
            429: lambda response: HttpResponseError(response=response, model=self._deserialize(models.Error, response)),
            503: lambda response: HttpResponseError(response=response, model=self._deserialize(models.Error, response)),
        }
        error_map.update(kwargs.pop('error_map', {}))
        api_version = "2020-09-21-preview2"
        accept = "application/json"

        # Construct URL
        url = self.get_chat_message.metadata['url']  # type: ignore
        path_format_arguments = {
            'endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
            'chatThreadId': self._serialize.url("chat_thread_id", chat_thread_id, 'str'),
            'chatMessageId': self._serialize.url("chat_message_id", chat_message_id, 'str'),
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}  # type: Dict[str, Any]
        query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')

        # Construct headers
        header_parameters = {}  # type: Dict[str, Any]
        header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')

        request = self._client.get(url, query_parameters, header_parameters)
        pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            raise HttpResponseError(response=response)

        deserialized = self._deserialize('ChatMessage', pipeline_response)

        if cls:
            return cls(pipeline_response, deserialized, {})

        return deserialized
    get_chat_message.metadata = {'url': '/chat/threads/{chatThreadId}/messages/{chatMessageId}'}  # type: ignore

    def update_chat_message(
        self,
        chat_thread_id,  # type: str
        chat_message_id,  # type: str
        body,  # type: "models.UpdateChatMessageRequest"
        **kwargs  # type: Any
    ):
        # type: (...) -> None
        """Updates a message.

        Updates a message.

        :param chat_thread_id: The thread id to which the message was sent.
        :type chat_thread_id: str
        :param chat_message_id: The message id.
        :type chat_message_id: str
        :param body: Details of the request to update the message.
        :type body: ~azure.communication.chat.models.UpdateChatMessageRequest
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: None, or the result of cls(response)
        :rtype: None
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        cls = kwargs.pop('cls', None)  # type: ClsType[None]
        error_map = {
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            401: lambda response: ClientAuthenticationError(response=response, model=self._deserialize(models.Error, response)),
            403: lambda response: HttpResponseError(response=response, model=self._deserialize(models.Error, response)),
            429: lambda response: HttpResponseError(response=response, model=self._deserialize(models.Error, response)),
            503: lambda response: HttpResponseError(response=response, model=self._deserialize(models.Error, response)),
        }
        error_map.update(kwargs.pop('error_map', {}))
        api_version = "2020-09-21-preview2"
        content_type = kwargs.pop("content_type", "application/json")
        accept = "application/json"

        # Construct URL
        url = self.update_chat_message.metadata['url']  # type: ignore
        path_format_arguments = {
            'endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
            'chatThreadId': self._serialize.url("chat_thread_id", chat_thread_id, 'str'),
            'chatMessageId': self._serialize.url("chat_message_id", chat_message_id, 'str'),
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}  # type: Dict[str, Any]
        query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')

        # Construct headers
        header_parameters = {}  # type: Dict[str, Any]
        header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')
        header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')

        body_content_kwargs = {}  # type: Dict[str, Any]
        body_content = self._serialize.body(body, 'UpdateChatMessageRequest')
        body_content_kwargs['content'] = body_content
        request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs)
        pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            raise HttpResponseError(response=response)

        if cls:
            return cls(pipeline_response, None, {})

    update_chat_message.metadata = {'url': '/chat/threads/{chatThreadId}/messages/{chatMessageId}'}  # type: ignore

    def delete_chat_message(
        self,
        chat_thread_id,  # type: str
        chat_message_id,  # type: str
        **kwargs  # type: Any
    ):
        # type: (...) -> None
        """Deletes a message.

        Deletes a message.

        :param chat_thread_id: The thread id to which the message was sent.
        :type chat_thread_id: str
        :param chat_message_id: The message id.
        :type chat_message_id: str
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: None, or the result of cls(response)
        :rtype: None
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        cls = kwargs.pop('cls', None)  # type: ClsType[None]
        error_map = {
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            401: lambda response: ClientAuthenticationError(response=response, model=self._deserialize(models.Error, response)),
            403: lambda response: HttpResponseError(response=response, model=self._deserialize(models.Error, response)),
            429: lambda response: HttpResponseError(response=response, model=self._deserialize(models.Error, response)),
            503: lambda response: HttpResponseError(response=response, model=self._deserialize(models.Error, response)),
        }
        error_map.update(kwargs.pop('error_map', {}))
        api_version = "2020-09-21-preview2"
        accept = "application/json"

        # Construct URL
        url = self.delete_chat_message.metadata['url']  # type: ignore
        path_format_arguments = {
            'endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
            'chatThreadId': self._serialize.url("chat_thread_id", chat_thread_id, 'str'),
            'chatMessageId': self._serialize.url("chat_message_id", chat_message_id, 'str'),
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}  # type: Dict[str, Any]
        query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')

        # Construct headers
        header_parameters = {}  # type: Dict[str, Any]
        header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')

        request = self._client.delete(url, query_parameters, header_parameters)
        pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
        response = pipeline_response.http_response

        if response.status_code not in [204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            raise HttpResponseError(response=response)

        if cls:
            return cls(pipeline_response, None, {})

    delete_chat_message.metadata = {'url': '/chat/threads/{chatThreadId}/messages/{chatMessageId}'}  # type: ignore

    def send_typing_notification(
        self,
        chat_thread_id,  # type: str
        **kwargs  # type: Any
    ):
        # type: (...) -> None
        """Posts a typing event to a thread, on behalf of a user.

        Posts a typing event to a thread, on behalf of a user.

        :param chat_thread_id: Id of the thread.
        :type chat_thread_id: str
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: None, or the result of cls(response)
        :rtype: None
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        cls = kwargs.pop('cls', None)  # type: ClsType[None]
        error_map = {
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            401: lambda response: ClientAuthenticationError(response=response, model=self._deserialize(models.Error, response)),
            403: lambda response: HttpResponseError(response=response, model=self._deserialize(models.Error, response)),
            429: lambda response: HttpResponseError(response=response, model=self._deserialize(models.Error, response)),
            503: lambda response: HttpResponseError(response=response, model=self._deserialize(models.Error, response)),
        }
        error_map.update(kwargs.pop('error_map', {}))
        api_version = "2020-09-21-preview2"
        accept = "application/json"

        # Construct URL
        url = self.send_typing_notification.metadata['url']  # type: ignore
        path_format_arguments = {
            'endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
            'chatThreadId': self._serialize.url("chat_thread_id", chat_thread_id, 'str'),
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}  # type: Dict[str, Any]
        query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')

        # Construct headers
        header_parameters = {}  # type: Dict[str, Any]
        header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')

        request = self._client.post(url, query_parameters, header_parameters)
        pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            raise HttpResponseError(response=response)

        if cls:
            return cls(pipeline_response, None, {})

    send_typing_notification.metadata = {'url': '/chat/threads/{chatThreadId}/typing'}  # type: ignore

    def list_chat_thread_members(
        self,
        chat_thread_id,  # type: str
        **kwargs  # type: Any
    ):
        # type: (...) -> Iterable["models.ChatThreadMembersCollection"]
        """Gets the members of a thread.

        Gets the members of a thread.

        :param chat_thread_id: Thread id to get members for.
        :type chat_thread_id: str
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: An iterator like instance of either ChatThreadMembersCollection or the result of cls(response)
        :rtype: ~azure.core.paging.ItemPaged[~azure.communication.chat.models.ChatThreadMembersCollection]
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        cls = kwargs.pop('cls', None)  # type: ClsType["models.ChatThreadMembersCollection"]
        error_map = {
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            401: lambda response: ClientAuthenticationError(response=response, model=self._deserialize(models.Error, response)),
            403: lambda response: HttpResponseError(response=response, model=self._deserialize(models.Error, response)),
            429: lambda response: HttpResponseError(response=response, model=self._deserialize(models.Error, response)),
            503: lambda response: HttpResponseError(response=response, model=self._deserialize(models.Error, response)),
        }
        error_map.update(kwargs.pop('error_map', {}))
        api_version = "2020-09-21-preview2"
        accept = "application/json"

        def prepare_request(next_link=None):
            # Construct headers
            header_parameters = {}  # type: Dict[str, Any]
            header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')

            if not next_link:
                # Construct URL
                url = self.list_chat_thread_members.metadata['url']  # type: ignore
                path_format_arguments = {
                    'endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
                    'chatThreadId': self._serialize.url("chat_thread_id", chat_thread_id, 'str'),
                }
                url = self._client.format_url(url, **path_format_arguments)
                # Construct parameters
                query_parameters = {}  # type: Dict[str, Any]
                query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')

                request = self._client.get(url, query_parameters, header_parameters)
            else:
                url = next_link
                query_parameters = {}  # type: Dict[str, Any]
                path_format_arguments = {
                    'endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
                    'chatThreadId': self._serialize.url("chat_thread_id", chat_thread_id, 'str'),
                }
                url = self._client.format_url(url, **path_format_arguments)
                request = self._client.get(url, query_parameters, header_parameters)
            return request

        def extract_data(pipeline_response):
            deserialized = self._deserialize('ChatThreadMembersCollection', pipeline_response)
            list_of_elem = deserialized.value
            if cls:
                list_of_elem = cls(list_of_elem)
            return deserialized.next_link or None, iter(list_of_elem)

        def get_next(next_link=None):
            request = prepare_request(next_link)

            pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                raise HttpResponseError(response=response)

            return pipeline_response

        return ItemPaged(
            get_next, extract_data
        )
    list_chat_thread_members.metadata = {'url': '/chat/threads/{chatThreadId}/members'}  # type: ignore

    def add_chat_thread_members(
        self,
        chat_thread_id,  # type: str
        body,  # type: "models.AddChatThreadMembersRequest"
        **kwargs  # type: Any
    ):
        # type: (...) -> None
        """Adds thread members to a thread. If members already exist, no change occurs.

        Adds thread members to a thread. If members already exist, no change occurs.

        :param chat_thread_id: Id of the thread to add members to.
        :type chat_thread_id: str
        :param body: Thread members to be added to the thread.
        :type body: ~azure.communication.chat.models.AddChatThreadMembersRequest
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: None, or the result of cls(response)
        :rtype: None
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        cls = kwargs.pop('cls', None)  # type: ClsType[None]
        error_map = {
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            401: lambda response: ClientAuthenticationError(response=response, model=self._deserialize(models.Error, response)),
            403: lambda response: HttpResponseError(response=response, model=self._deserialize(models.Error, response)),
            429: lambda response: HttpResponseError(response=response, model=self._deserialize(models.Error, response)),
            503: lambda response: HttpResponseError(response=response, model=self._deserialize(models.Error, response)),
        }
        error_map.update(kwargs.pop('error_map', {}))
        api_version = "2020-09-21-preview2"
        content_type = kwargs.pop("content_type", "application/json")
        accept = "application/json"

        # Construct URL
        url = self.add_chat_thread_members.metadata['url']  # type: ignore
        path_format_arguments = {
            'endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
            'chatThreadId': self._serialize.url("chat_thread_id", chat_thread_id, 'str'),
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}  # type: Dict[str, Any]
        query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')

        # Construct headers
        header_parameters = {}  # type: Dict[str, Any]
        header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')
        header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')

        body_content_kwargs = {}  # type: Dict[str, Any]
        body_content = self._serialize.body(body, 'AddChatThreadMembersRequest')
        body_content_kwargs['content'] = body_content
        request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs)
        pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
        response = pipeline_response.http_response

        if response.status_code not in [207]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            raise HttpResponseError(response=response)

        if cls:
            return cls(pipeline_response, None, {})

    add_chat_thread_members.metadata = {'url': '/chat/threads/{chatThreadId}/members'}  # type: ignore

    def remove_chat_thread_member(
        self,
        chat_thread_id,  # type: str
        chat_member_id,  # type: str
        **kwargs  # type: Any
    ):
        # type: (...) -> None
        """Remove a member from a thread.

        Remove a member from a thread.

        :param chat_thread_id: Thread id to remove the member from.
        :type chat_thread_id: str
        :param chat_member_id: Id of the thread member to remove from the thread.
        :type chat_member_id: str
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: None, or the result of cls(response)
        :rtype: None
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        cls = kwargs.pop('cls', None)  # type: ClsType[None]
        error_map = {
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            401: lambda response: ClientAuthenticationError(response=response, model=self._deserialize(models.Error, response)),
            403: lambda response: HttpResponseError(response=response, model=self._deserialize(models.Error, response)),
            429: lambda response: HttpResponseError(response=response, model=self._deserialize(models.Error, response)),
            503: lambda response: HttpResponseError(response=response, model=self._deserialize(models.Error, response)),
        }
        error_map.update(kwargs.pop('error_map', {}))
        api_version = "2020-09-21-preview2"
        accept = "application/json"

        # Construct URL
        url = self.remove_chat_thread_member.metadata['url']  # type: ignore
        path_format_arguments = {
            'endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
            'chatThreadId': self._serialize.url("chat_thread_id", chat_thread_id, 'str'),
            'chatMemberId': self._serialize.url("chat_member_id", chat_member_id, 'str'),
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}  # type: Dict[str, Any]
        query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')

        # Construct headers
        header_parameters = {}  # type: Dict[str, Any]
        header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')

        request = self._client.delete(url, query_parameters, header_parameters)
        pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
        response = pipeline_response.http_response

        if response.status_code not in [204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            raise HttpResponseError(response=response)

        if cls:
            return cls(pipeline_response, None, {})

    remove_chat_thread_member.metadata = {'url': '/chat/threads/{chatThreadId}/members/{chatMemberId}'}  # type: ignore

    def create_chat_thread(
        self,
        body,  # type: "models.CreateChatThreadRequest"
        **kwargs  # type: Any
    ):
        # type: (...) -> "models.MultiStatusResponse"
        """Creates a chat thread.

        Creates a chat thread.

        :param body: Request payload for creating a chat thread.
        :type body: ~azure.communication.chat.models.CreateChatThreadRequest
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: MultiStatusResponse, or the result of cls(response)
        :rtype: ~azure.communication.chat.models.MultiStatusResponse
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        cls = kwargs.pop('cls', None)  # type: ClsType["models.MultiStatusResponse"]
        error_map = {
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            401: lambda response: ClientAuthenticationError(response=response, model=self._deserialize(models.Error, response)),
            403: lambda response: HttpResponseError(response=response, model=self._deserialize(models.Error, response)),
            429: lambda response: HttpResponseError(response=response, model=self._deserialize(models.Error, response)),
            503: lambda response: HttpResponseError(response=response, model=self._deserialize(models.Error, response)),
        }
        error_map.update(kwargs.pop('error_map', {}))
        api_version = "2020-09-21-preview2"
        content_type = kwargs.pop("content_type", "application/json")
        accept = "application/json"

        # Construct URL
        url = self.create_chat_thread.metadata['url']  # type: ignore
        path_format_arguments = {
            'endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}  # type: Dict[str, Any]
        query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')

        # Construct headers
        header_parameters = {}  # type: Dict[str, Any]
        header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')
        header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')

        body_content_kwargs = {}  # type: Dict[str, Any]
        body_content = self._serialize.body(body, 'CreateChatThreadRequest')
        body_content_kwargs['content'] = body_content
        request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs)
        pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
        response = pipeline_response.http_response

        if response.status_code not in [207]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            raise HttpResponseError(response=response)

        deserialized = self._deserialize('MultiStatusResponse', pipeline_response)

        if cls:
            return cls(pipeline_response, deserialized, {})

        return deserialized
    create_chat_thread.metadata = {'url': '/chat/threads'}  # type: ignore

    def list_chat_threads(
        self,
        max_page_size=None,  # type: Optional[int]
        start_time=None,  # type: Optional[datetime.datetime]
        **kwargs  # type: Any
    ):
        # type: (...) -> Iterable["models.ChatThreadsInfoCollection"]
        """Gets the list of chat threads of a user.

        Gets the list of chat threads of a user.

        :param max_page_size: The maximum number of chat threads returned per page.
        :type max_page_size: int
        :param start_time: The earliest point in time to get chat threads up to. The timestamp should
         be in ISO8601 format: ``yyyy-MM-ddTHH:mm:ssZ``.
        :type start_time: ~datetime.datetime
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: An iterator like instance of either ChatThreadsInfoCollection or the result of cls(response)
        :rtype: ~azure.core.paging.ItemPaged[~azure.communication.chat.models.ChatThreadsInfoCollection]
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        cls = kwargs.pop('cls', None)  # type: ClsType["models.ChatThreadsInfoCollection"]
        error_map = {
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            401: lambda response: ClientAuthenticationError(response=response, model=self._deserialize(models.Error, response)),
            403: lambda response: HttpResponseError(response=response, model=self._deserialize(models.Error, response)),
            429: lambda response: HttpResponseError(response=response, model=self._deserialize(models.Error, response)),
            503: lambda response: HttpResponseError(response=response, model=self._deserialize(models.Error, response)),
        }
        error_map.update(kwargs.pop('error_map', {}))
        api_version = "2020-09-21-preview2"
        accept = "application/json"

        def prepare_request(next_link=None):
            # Construct headers
            header_parameters = {}  # type: Dict[str, Any]
            header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')

            if not next_link:
                # Construct URL
                url = self.list_chat_threads.metadata['url']  # type: ignore
                path_format_arguments = {
                    'endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
                }
                url = self._client.format_url(url, **path_format_arguments)
                # Construct parameters
                query_parameters = {}  # type: Dict[str, Any]
                if max_page_size is not None:
                    query_parameters['maxPageSize'] = self._serialize.query("max_page_size", max_page_size, 'int')
                if start_time is not None:
                    query_parameters['startTime'] = self._serialize.query("start_time", start_time, 'iso-8601')
                query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')

                request = self._client.get(url, query_parameters, header_parameters)
            else:
                url = next_link
                query_parameters = {}  # type: Dict[str, Any]
                path_format_arguments = {
                    'endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
                }
                url = self._client.format_url(url, **path_format_arguments)
                request = self._client.get(url, query_parameters, header_parameters)
            return request

        def extract_data(pipeline_response):
            deserialized = self._deserialize('ChatThreadsInfoCollection', pipeline_response)
            list_of_elem = deserialized.value
            if cls:
                list_of_elem = cls(list_of_elem)
            return deserialized.next_link or None, iter(list_of_elem)

        def get_next(next_link=None):
            request = prepare_request(next_link)

            pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                raise HttpResponseError(response=response)

            return pipeline_response

        return ItemPaged(
            get_next, extract_data
        )
    list_chat_threads.metadata = {'url': '/chat/threads'}  # type: ignore

    def update_chat_thread(
        self,
        chat_thread_id,  # type: str
        body,  # type: "models.UpdateChatThreadRequest"
        **kwargs  # type: Any
    ):
        # type: (...) -> None
        """Updates a thread's properties.

        Updates a thread's properties.

        :param chat_thread_id: The id of the thread to update.
        :type chat_thread_id: str
        :param body: Request payload for updating a chat thread.
        :type body: ~azure.communication.chat.models.UpdateChatThreadRequest
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: None, or the result of cls(response)
        :rtype: None
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        cls = kwargs.pop('cls', None)  # type: ClsType[None]
        error_map = {
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            401: lambda response: ClientAuthenticationError(response=response, model=self._deserialize(models.Error, response)),
            403: lambda response: HttpResponseError(response=response, model=self._deserialize(models.Error, response)),
            429: lambda response: HttpResponseError(response=response, model=self._deserialize(models.Error, response)),
            503: lambda response: HttpResponseError(response=response, model=self._deserialize(models.Error, response)),
        }
        error_map.update(kwargs.pop('error_map', {}))
        api_version = "2020-09-21-preview2"
        content_type = kwargs.pop("content_type", "application/json")
        accept = "application/json"

        # Construct URL
        url = self.update_chat_thread.metadata['url']  # type: ignore
        path_format_arguments = {
            'endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
            'chatThreadId': self._serialize.url("chat_thread_id", chat_thread_id, 'str'),
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}  # type: Dict[str, Any]
        query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')

        # Construct headers
        header_parameters = {}  # type: Dict[str, Any]
        header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')
        header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')

        body_content_kwargs = {}  # type: Dict[str, Any]
        body_content = self._serialize.body(body, 'UpdateChatThreadRequest')
        body_content_kwargs['content'] = body_content
        request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs)
        pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            raise HttpResponseError(response=response)

        if cls:
            return cls(pipeline_response, None, {})

    update_chat_thread.metadata = {'url': '/chat/threads/{chatThreadId}'}  # type: ignore

    def get_chat_thread(
        self,
        chat_thread_id,  # type: str
        **kwargs  # type: Any
    ):
        # type: (...) -> "models.ChatThread"
        """Gets a chat thread.

        Gets a chat thread.

        :param chat_thread_id: Thread id to get.
        :type chat_thread_id: str
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: ChatThread, or the result of cls(response)
        :rtype: ~azure.communication.chat.models.ChatThread
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        cls = kwargs.pop('cls', None)  # type: ClsType["models.ChatThread"]
        error_map = {
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            401: lambda response: ClientAuthenticationError(response=response, model=self._deserialize(models.Error, response)),
            403: lambda response: HttpResponseError(response=response, model=self._deserialize(models.Error, response)),
            429: lambda response: HttpResponseError(response=response, model=self._deserialize(models.Error, response)),
            503: lambda response: HttpResponseError(response=response, model=self._deserialize(models.Error, response)),
        }
        error_map.update(kwargs.pop('error_map', {}))
        api_version = "2020-09-21-preview2"
        accept = "application/json"

        # Construct URL
        url = self.get_chat_thread.metadata['url']  # type: ignore
        path_format_arguments = {
            'endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
            'chatThreadId': self._serialize.url("chat_thread_id", chat_thread_id, 'str'),
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}  # type: Dict[str, Any]
        query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')

        # Construct headers
        header_parameters = {}  # type: Dict[str, Any]
        header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')

        request = self._client.get(url, query_parameters, header_parameters)
        pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            raise HttpResponseError(response=response)

        deserialized = self._deserialize('ChatThread', pipeline_response)

        if cls:
            return cls(pipeline_response, deserialized, {})

        return deserialized
    get_chat_thread.metadata = {'url': '/chat/threads/{chatThreadId}'}  # type: ignore

    def delete_chat_thread(
        self,
        chat_thread_id,  # type: str
        **kwargs  # type: Any
    ):
        # type: (...) -> None
        """Deletes a thread.

        Deletes a thread.

        :param chat_thread_id: Thread id to delete.
        :type chat_thread_id: str
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: None, or the result of cls(response)
        :rtype: None
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        cls = kwargs.pop('cls', None)  # type: ClsType[None]
        error_map = {
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            401: lambda response: ClientAuthenticationError(response=response, model=self._deserialize(models.Error, response)),
            403: lambda response: HttpResponseError(response=response, model=self._deserialize(models.Error, response)),
            429: lambda response: HttpResponseError(response=response, model=self._deserialize(models.Error, response)),
            503: lambda response: HttpResponseError(response=response, model=self._deserialize(models.Error, response)),
        }
        error_map.update(kwargs.pop('error_map', {}))
        api_version = "2020-09-21-preview2"
        accept = "application/json"

        # Construct URL
        url = self.delete_chat_thread.metadata['url']  # type: ignore
        path_format_arguments = {
            'endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
            'chatThreadId': self._serialize.url("chat_thread_id", chat_thread_id, 'str'),
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}  # type: Dict[str, Any]
        query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')

        # Construct headers
        header_parameters = {}  # type: Dict[str, Any]
        header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')

        request = self._client.delete(url, query_parameters, header_parameters)
        pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
        response = pipeline_response.http_response

        if response.status_code not in [204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            raise HttpResponseError(response=response)

        if cls:
            return cls(pipeline_response, None, {})

    delete_chat_thread.metadata = {'url': '/chat/threads/{chatThreadId}'}  # type: ignore
