# pylint: disable=too-many-lines
# 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.
# --------------------------------------------------------------------------
from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast

from .....aio._async_polling import AsyncDocumentModelAdministrationClientLROPoller
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse
from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod
from azure.core.polling.async_base_polling import AsyncLROBasePolling
from azure.core.rest import 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 ... import models as _models
from ..._vendor import _convert_request
from ...operations._form_recognizer_client_operations import build_analyze_document_request_initial, build_authorize_copy_document_model_request, build_build_document_model_request_initial, build_compose_document_model_request_initial, build_copy_document_model_to_request_initial, build_delete_document_model_request, build_get_analyze_document_result_request, build_get_document_model_request, build_get_document_models_request, build_get_operation_request, build_get_operations_request, build_get_resource_details_request
from .._vendor import MixinABC
T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]

class FormRecognizerClientOperationsMixin(MixinABC):

    async def _analyze_document_initial(  # pylint: disable=inconsistent-return-statements
        self,
        model_id: str,
        pages: Optional[str] = None,
        locale: Optional[str] = None,
        string_index_type: Optional[Union[str, "_models.StringIndexType"]] = None,
        analyze_request: Optional[Union[IO, _models.AnalyzeDocumentRequest]] = None,
        *,
        content_type: Optional[Union[str, "_models.ContentType"]] = "application/json",
        **kwargs: Any
    ) -> None:
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}) or {})

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

        api_version = kwargs.pop('api_version', _params.pop('api-version', "2022-08-31"))  # type: str
        cls = kwargs.pop('cls', None)  # type: ClsType[None]

        _json = None
        _content = None
        content_type = content_type or ""
        if content_type.split(";")[0] in ['application/json']:
            if analyze_request is not None:
                _json = self._serialize.body(analyze_request, 'AnalyzeDocumentRequest')
        elif content_type.split(";")[0] in ['application/octet-stream', 'application/pdf', 'image/bmp', 'image/heif', 'image/jpeg', 'image/png', 'image/tiff']:
            _content = analyze_request
        else:
            raise ValueError(
                "The content_type '{}' is not one of the allowed values: "
                "['application/octet-stream', 'application/pdf', 'image/bmp', 'image/heif', 'image/jpeg', 'image/png', 'image/tiff', 'application/json']".format(content_type)
            )

        request = build_analyze_document_request_initial(
            model_id=model_id,
            api_version=api_version,
            content_type=content_type,
            json=_json,
            content=_content,
            pages=pages,
            locale=locale,
            string_index_type=string_index_type,
            template_url=self._analyze_document_initial.metadata['url'],
            headers=_headers,
            params=_params,
        )
        request = _convert_request(request)
        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)  # type: ignore

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

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

        response_headers = {}
        response_headers['Operation-Location']=self._deserialize('str', response.headers.get('Operation-Location'))


        if cls:
            return cls(pipeline_response, None, response_headers)

    _analyze_document_initial.metadata = {'url': "/documentModels/{modelId}:analyze"}  # type: ignore


    @distributed_trace_async
    async def begin_analyze_document(  # pylint: disable=inconsistent-return-statements
        self,
        model_id: str,
        pages: Optional[str] = None,
        locale: Optional[str] = None,
        string_index_type: Optional[Union[str, "_models.StringIndexType"]] = None,
        analyze_request: Optional[Union[IO, _models.AnalyzeDocumentRequest]] = None,
        *,
        content_type: Optional[Union[str, "_models.ContentType"]] = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[None]:
        """Analyze document.

        Analyzes document with document model.

        :param model_id: Unique document model name.
        :type model_id: str
        :param pages: List of 1-based page numbers to analyze.  Ex. "1-3,5,7-9". Default value is None.
        :type pages: str
        :param locale: Locale hint for text recognition and document analysis.  Value may contain only
         the language code (ex. "en", "fr") or BCP 47 language tag (ex. "en-US"). Default value is None.
        :type locale: str
        :param string_index_type: Method used to compute string offset and length. Default value is
         None.
        :type string_index_type: str or ~azure.ai.formrecognizer.v2022_08_31.models.StringIndexType
        :param analyze_request: Analyze request parameters. Default value is None.
        :type analyze_request: IO or ~azure.ai.formrecognizer.v2022_08_31.models.AnalyzeDocumentRequest
        :keyword content_type: Media type of the body sent to the API. Known values are:
         "application/octet-stream", "application/pdf", "image/bmp", "image/heif", "image/jpeg",
         "image/png", "image/tiff", and "application/json". Default value is "application/json".
        :paramtype content_type: str or ~azure.ai.formrecognizer.v2022_08_31.models.ContentType
        :keyword callable cls: A custom type or function that will be passed the direct response
        :keyword str continuation_token: A continuation token to restart a poller from a saved state.
        :keyword polling: By default, your polling method will be AsyncLROBasePolling. Pass in False
         for this operation to not poll, or pass in your own initialized polling object for a personal
         polling strategy.
        :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
        :keyword int polling_interval: Default waiting time between two polls for LRO operations if no
         Retry-After header is present.
        :return: An instance of AsyncLROPoller that returns either None or the result of cls(response)
        :rtype: ~azure.core.polling.AsyncLROPoller[None]
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version = kwargs.pop('api_version', _params.pop('api-version', "2022-08-31"))  # type: str
        cls = kwargs.pop('cls', None)  # type: ClsType[None]
        polling = kwargs.pop('polling', True)  # type: Union[bool, AsyncPollingMethod]
        lro_delay = kwargs.pop(
            'polling_interval',
            self._config.polling_interval
        )
        cont_token = kwargs.pop('continuation_token', None)  # type: Optional[str]
        if cont_token is None:
            raw_result = await self._analyze_document_initial(  # type: ignore
                model_id=model_id,
                pages=pages,
                locale=locale,
                string_index_type=string_index_type,
                analyze_request=analyze_request,
                content_type=content_type,
                api_version=api_version,
                cls=lambda x,y,z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
        kwargs.pop('error_map', None)

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


        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
        }

        if polling is True:
            polling_method = cast(AsyncPollingMethod, AsyncLROBasePolling(
                lro_delay,
                
                path_format_arguments=path_format_arguments,
                **kwargs
        ))  # type: AsyncPollingMethod
        elif polling is False: polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else: polling_method = polling
        if cont_token:
            return AsyncLROPoller.from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output
            )
        return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)

    begin_analyze_document.metadata = {'url': "/documentModels/{modelId}:analyze"}  # type: ignore

    @distributed_trace_async
    async def get_analyze_document_result(
        self,
        model_id: str,
        result_id: str,
        **kwargs: Any
    ) -> _models.AnalyzeResultOperation:
        """Get analyze result.

        Gets the result of document analysis.

        :param model_id: Unique document model name.
        :type model_id: str
        :param result_id: Analyze operation result ID.
        :type result_id: str
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: AnalyzeResultOperation, or the result of cls(response)
        :rtype: ~azure.ai.formrecognizer.v2022_08_31.models.AnalyzeResultOperation
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}) or {})

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

        api_version = kwargs.pop('api_version', _params.pop('api-version', "2022-08-31"))  # type: str
        cls = kwargs.pop('cls', None)  # type: ClsType[_models.AnalyzeResultOperation]

        
        request = build_get_analyze_document_result_request(
            model_id=model_id,
            result_id=result_id,
            api_version=api_version,
            template_url=self.get_analyze_document_result.metadata['url'],
            headers=_headers,
            params=_params,
        )
        request = _convert_request(request)
        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)  # type: ignore

        pipeline_response = await self._client._pipeline.run(  # type: ignore # pylint: disable=protected-access
            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)
            error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
            raise HttpResponseError(response=response, model=error)

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

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

        return deserialized

    get_analyze_document_result.metadata = {'url': "/documentModels/{modelId}/analyzeResults/{resultId}"}  # type: ignore


    async def _build_document_model_initial(  # pylint: disable=inconsistent-return-statements
        self,
        build_request: _models.BuildDocumentModelRequest,
        **kwargs: Any
    ) -> None:
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}) or {})

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

        api_version = kwargs.pop('api_version', _params.pop('api-version', "2022-08-31"))  # type: str
        content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json"))  # type: Optional[str]
        cls = kwargs.pop('cls', None)  # type: ClsType[None]

        _json = self._serialize.body(build_request, 'BuildDocumentModelRequest')

        request = build_build_document_model_request_initial(
            api_version=api_version,
            content_type=content_type,
            json=_json,
            template_url=self._build_document_model_initial.metadata['url'],
            headers=_headers,
            params=_params,
        )
        request = _convert_request(request)
        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)  # type: ignore

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

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

        response_headers = {}
        response_headers['Operation-Location']=self._deserialize('str', response.headers.get('Operation-Location'))


        if cls:
            return cls(pipeline_response, None, response_headers)

    _build_document_model_initial.metadata = {'url': "/documentModels:build"}  # type: ignore


    @distributed_trace_async
    async def begin_build_document_model(  # pylint: disable=inconsistent-return-statements
        self,
        build_request: _models.BuildDocumentModelRequest,
        **kwargs: Any
    ) -> AsyncDocumentModelAdministrationClientLROPoller[None]:
        """Build document model.

        Builds a custom document analysis model.

        :param build_request: Building request parameters.
        :type build_request: ~azure.ai.formrecognizer.v2022_08_31.models.BuildDocumentModelRequest
        :keyword callable cls: A custom type or function that will be passed the direct response
        :keyword str continuation_token: A continuation token to restart a poller from a saved state.
        :keyword polling: By default, your polling method will be AsyncLROBasePolling. Pass in False
         for this operation to not poll, or pass in your own initialized polling object for a personal
         polling strategy.
        :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
        :keyword int polling_interval: Default waiting time between two polls for LRO operations if no
         Retry-After header is present.
        :return: An instance of AsyncDocumentModelAdministrationClientLROPoller that returns either
         None or the result of cls(response)
        :rtype: ~.....aio._async_polling.AsyncDocumentModelAdministrationClientLROPoller[None]
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version = kwargs.pop('api_version', _params.pop('api-version', "2022-08-31"))  # type: str
        content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json"))  # type: Optional[str]
        cls = kwargs.pop('cls', None)  # type: ClsType[None]
        polling = kwargs.pop('polling', True)  # type: Union[bool, AsyncPollingMethod]
        lro_delay = kwargs.pop(
            'polling_interval',
            self._config.polling_interval
        )
        cont_token = kwargs.pop('continuation_token', None)  # type: Optional[str]
        if cont_token is None:
            raw_result = await self._build_document_model_initial(  # type: ignore
                build_request=build_request,
                api_version=api_version,
                content_type=content_type,
                cls=lambda x,y,z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
        kwargs.pop('error_map', None)

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


        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
        }

        if polling is True:
            polling_method = cast(AsyncPollingMethod, AsyncLROBasePolling(
                lro_delay,
                
                path_format_arguments=path_format_arguments,
                **kwargs
        ))  # type: AsyncPollingMethod
        elif polling is False: polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else: polling_method = polling
        if cont_token:
            return AsyncDocumentModelAdministrationClientLROPoller.from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output
            )
        return AsyncDocumentModelAdministrationClientLROPoller(self._client, raw_result, get_long_running_output, polling_method)

    begin_build_document_model.metadata = {'url': "/documentModels:build"}  # type: ignore

    async def _compose_document_model_initial(  # pylint: disable=inconsistent-return-statements
        self,
        compose_request: _models.ComposeDocumentModelRequest,
        **kwargs: Any
    ) -> None:
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}) or {})

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

        api_version = kwargs.pop('api_version', _params.pop('api-version', "2022-08-31"))  # type: str
        content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json"))  # type: Optional[str]
        cls = kwargs.pop('cls', None)  # type: ClsType[None]

        _json = self._serialize.body(compose_request, 'ComposeDocumentModelRequest')

        request = build_compose_document_model_request_initial(
            api_version=api_version,
            content_type=content_type,
            json=_json,
            template_url=self._compose_document_model_initial.metadata['url'],
            headers=_headers,
            params=_params,
        )
        request = _convert_request(request)
        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)  # type: ignore

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

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

        response_headers = {}
        response_headers['Operation-Location']=self._deserialize('str', response.headers.get('Operation-Location'))


        if cls:
            return cls(pipeline_response, None, response_headers)

    _compose_document_model_initial.metadata = {'url': "/documentModels:compose"}  # type: ignore


    @distributed_trace_async
    async def begin_compose_document_model(  # pylint: disable=inconsistent-return-statements
        self,
        compose_request: _models.ComposeDocumentModelRequest,
        **kwargs: Any
    ) -> AsyncDocumentModelAdministrationClientLROPoller[None]:
        """Compose document model.

        Creates a new document model from document types of existing document models.

        :param compose_request: Compose request parameters.
        :type compose_request: ~azure.ai.formrecognizer.v2022_08_31.models.ComposeDocumentModelRequest
        :keyword callable cls: A custom type or function that will be passed the direct response
        :keyword str continuation_token: A continuation token to restart a poller from a saved state.
        :keyword polling: By default, your polling method will be AsyncLROBasePolling. Pass in False
         for this operation to not poll, or pass in your own initialized polling object for a personal
         polling strategy.
        :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
        :keyword int polling_interval: Default waiting time between two polls for LRO operations if no
         Retry-After header is present.
        :return: An instance of AsyncDocumentModelAdministrationClientLROPoller that returns either
         None or the result of cls(response)
        :rtype: ~.....aio._async_polling.AsyncDocumentModelAdministrationClientLROPoller[None]
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version = kwargs.pop('api_version', _params.pop('api-version', "2022-08-31"))  # type: str
        content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json"))  # type: Optional[str]
        cls = kwargs.pop('cls', None)  # type: ClsType[None]
        polling = kwargs.pop('polling', True)  # type: Union[bool, AsyncPollingMethod]
        lro_delay = kwargs.pop(
            'polling_interval',
            self._config.polling_interval
        )
        cont_token = kwargs.pop('continuation_token', None)  # type: Optional[str]
        if cont_token is None:
            raw_result = await self._compose_document_model_initial(  # type: ignore
                compose_request=compose_request,
                api_version=api_version,
                content_type=content_type,
                cls=lambda x,y,z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
        kwargs.pop('error_map', None)

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


        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
        }

        if polling is True:
            polling_method = cast(AsyncPollingMethod, AsyncLROBasePolling(
                lro_delay,
                
                path_format_arguments=path_format_arguments,
                **kwargs
        ))  # type: AsyncPollingMethod
        elif polling is False: polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else: polling_method = polling
        if cont_token:
            return AsyncDocumentModelAdministrationClientLROPoller.from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output
            )
        return AsyncDocumentModelAdministrationClientLROPoller(self._client, raw_result, get_long_running_output, polling_method)

    begin_compose_document_model.metadata = {'url': "/documentModels:compose"}  # type: ignore

    @distributed_trace_async
    async def authorize_copy_document_model(
        self,
        authorize_copy_request: _models.AuthorizeCopyRequest,
        **kwargs: Any
    ) -> _models.CopyAuthorization:
        """Generate copy authorization.

        Generates authorization to copy a document model to this location with specified modelId and
        optional description.

        :param authorize_copy_request: Authorize copy request parameters.
        :type authorize_copy_request: ~azure.ai.formrecognizer.v2022_08_31.models.AuthorizeCopyRequest
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: CopyAuthorization, or the result of cls(response)
        :rtype: ~azure.ai.formrecognizer.v2022_08_31.models.CopyAuthorization
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}) or {})

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

        api_version = kwargs.pop('api_version', _params.pop('api-version', "2022-08-31"))  # type: str
        content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json"))  # type: Optional[str]
        cls = kwargs.pop('cls', None)  # type: ClsType[_models.CopyAuthorization]

        _json = self._serialize.body(authorize_copy_request, 'AuthorizeCopyRequest')

        request = build_authorize_copy_document_model_request(
            api_version=api_version,
            content_type=content_type,
            json=_json,
            template_url=self.authorize_copy_document_model.metadata['url'],
            headers=_headers,
            params=_params,
        )
        request = _convert_request(request)
        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)  # type: ignore

        pipeline_response = await self._client._pipeline.run(  # type: ignore # pylint: disable=protected-access
            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)
            error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
            raise HttpResponseError(response=response, model=error)

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

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

        return deserialized

    authorize_copy_document_model.metadata = {'url': "/documentModels:authorizeCopy"}  # type: ignore


    async def _copy_document_model_to_initial(  # pylint: disable=inconsistent-return-statements
        self,
        model_id: str,
        copy_to_request: _models.CopyAuthorization,
        **kwargs: Any
    ) -> None:
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}) or {})

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

        api_version = kwargs.pop('api_version', _params.pop('api-version', "2022-08-31"))  # type: str
        content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json"))  # type: Optional[str]
        cls = kwargs.pop('cls', None)  # type: ClsType[None]

        _json = self._serialize.body(copy_to_request, 'CopyAuthorization')

        request = build_copy_document_model_to_request_initial(
            model_id=model_id,
            api_version=api_version,
            content_type=content_type,
            json=_json,
            template_url=self._copy_document_model_to_initial.metadata['url'],
            headers=_headers,
            params=_params,
        )
        request = _convert_request(request)
        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)  # type: ignore

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

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

        response_headers = {}
        response_headers['Operation-Location']=self._deserialize('str', response.headers.get('Operation-Location'))


        if cls:
            return cls(pipeline_response, None, response_headers)

    _copy_document_model_to_initial.metadata = {'url': "/documentModels/{modelId}:copyTo"}  # type: ignore


    @distributed_trace_async
    async def begin_copy_document_model_to(  # pylint: disable=inconsistent-return-statements
        self,
        model_id: str,
        copy_to_request: _models.CopyAuthorization,
        **kwargs: Any
    ) -> AsyncDocumentModelAdministrationClientLROPoller[None]:
        """Copy document model.

        Copies document model to the target resource, region, and modelId.

        :param model_id: Unique document model name.
        :type model_id: str
        :param copy_to_request: Copy to request parameters.
        :type copy_to_request: ~azure.ai.formrecognizer.v2022_08_31.models.CopyAuthorization
        :keyword callable cls: A custom type or function that will be passed the direct response
        :keyword str continuation_token: A continuation token to restart a poller from a saved state.
        :keyword polling: By default, your polling method will be AsyncLROBasePolling. Pass in False
         for this operation to not poll, or pass in your own initialized polling object for a personal
         polling strategy.
        :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
        :keyword int polling_interval: Default waiting time between two polls for LRO operations if no
         Retry-After header is present.
        :return: An instance of AsyncDocumentModelAdministrationClientLROPoller that returns either
         None or the result of cls(response)
        :rtype: ~.....aio._async_polling.AsyncDocumentModelAdministrationClientLROPoller[None]
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version = kwargs.pop('api_version', _params.pop('api-version', "2022-08-31"))  # type: str
        content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json"))  # type: Optional[str]
        cls = kwargs.pop('cls', None)  # type: ClsType[None]
        polling = kwargs.pop('polling', True)  # type: Union[bool, AsyncPollingMethod]
        lro_delay = kwargs.pop(
            'polling_interval',
            self._config.polling_interval
        )
        cont_token = kwargs.pop('continuation_token', None)  # type: Optional[str]
        if cont_token is None:
            raw_result = await self._copy_document_model_to_initial(  # type: ignore
                model_id=model_id,
                copy_to_request=copy_to_request,
                api_version=api_version,
                content_type=content_type,
                cls=lambda x,y,z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
        kwargs.pop('error_map', None)

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


        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
        }

        if polling is True:
            polling_method = cast(AsyncPollingMethod, AsyncLROBasePolling(
                lro_delay,
                
                path_format_arguments=path_format_arguments,
                **kwargs
        ))  # type: AsyncPollingMethod
        elif polling is False: polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
        else: polling_method = polling
        if cont_token:
            return AsyncDocumentModelAdministrationClientLROPoller.from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output
            )
        return AsyncDocumentModelAdministrationClientLROPoller(self._client, raw_result, get_long_running_output, polling_method)

    begin_copy_document_model_to.metadata = {'url': "/documentModels/{modelId}:copyTo"}  # type: ignore

    @distributed_trace
    def get_operations(
        self,
        **kwargs: Any
    ) -> AsyncIterable[_models.GetOperationsResponse]:
        """List operations.

        Lists all operations.

        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: An iterator like instance of either GetOperationsResponse or the result of
         cls(response)
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.ai.formrecognizer.v2022_08_31.models.GetOperationsResponse]
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version = kwargs.pop('api_version', _params.pop('api-version', "2022-08-31"))  # type: str
        cls = kwargs.pop('cls', None)  # type: ClsType[_models.GetOperationsResponse]

        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}) or {})
        def prepare_request(next_link=None):
            if not next_link:
                
                request = build_get_operations_request(
                    api_version=api_version,
                    template_url=self.get_operations.metadata['url'],
                    headers=_headers,
                    params=_params,
                )
                request = _convert_request(request)
                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)  # type: ignore

            else:
                
                request = build_get_operations_request(
                    api_version=api_version,
                    template_url=next_link,
                    headers=_headers,
                    params=_params,
                )
                request = _convert_request(request)
                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)  # type: ignore

                path_format_arguments = {
                    "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
                }
                request.method = "GET"
            return request

        async def extract_data(pipeline_response):
            deserialized = self._deserialize("GetOperationsResponse", pipeline_response)
            list_of_elem = deserialized.value
            if cls:
                list_of_elem = cls(list_of_elem)
            return deserialized.next_link or None, AsyncList(list_of_elem)

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

            pipeline_response = await self._client._pipeline.run(  # pylint: disable=protected-access
                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)
                error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
                raise HttpResponseError(response=response, model=error)

            return pipeline_response


        return AsyncItemPaged(
            get_next, extract_data
        )
    get_operations.metadata = {'url': "/operations"}  # type: ignore

    @distributed_trace_async
    async def get_operation(
        self,
        operation_id: str,
        **kwargs: Any
    ) -> _models.OperationDetails:
        """Get operation.

        Gets operation info.

        :param operation_id: Unique operation ID.
        :type operation_id: str
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: OperationDetails, or the result of cls(response)
        :rtype: ~azure.ai.formrecognizer.v2022_08_31.models.OperationDetails
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}) or {})

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

        api_version = kwargs.pop('api_version', _params.pop('api-version', "2022-08-31"))  # type: str
        cls = kwargs.pop('cls', None)  # type: ClsType[_models.OperationDetails]

        
        request = build_get_operation_request(
            operation_id=operation_id,
            api_version=api_version,
            template_url=self.get_operation.metadata['url'],
            headers=_headers,
            params=_params,
        )
        request = _convert_request(request)
        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)  # type: ignore

        pipeline_response = await self._client._pipeline.run(  # type: ignore # pylint: disable=protected-access
            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)
            error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
            raise HttpResponseError(response=response, model=error)

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

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

        return deserialized

    get_operation.metadata = {'url': "/operations/{operationId}"}  # type: ignore


    @distributed_trace
    def get_document_models(
        self,
        **kwargs: Any
    ) -> AsyncIterable[_models.GetDocumentModelsResponse]:
        """List document models.

        List all document models.

        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: An iterator like instance of either GetDocumentModelsResponse or the result of
         cls(response)
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.ai.formrecognizer.v2022_08_31.models.GetDocumentModelsResponse]
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version = kwargs.pop('api_version', _params.pop('api-version', "2022-08-31"))  # type: str
        cls = kwargs.pop('cls', None)  # type: ClsType[_models.GetDocumentModelsResponse]

        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}) or {})
        def prepare_request(next_link=None):
            if not next_link:
                
                request = build_get_document_models_request(
                    api_version=api_version,
                    template_url=self.get_document_models.metadata['url'],
                    headers=_headers,
                    params=_params,
                )
                request = _convert_request(request)
                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)  # type: ignore

            else:
                
                request = build_get_document_models_request(
                    api_version=api_version,
                    template_url=next_link,
                    headers=_headers,
                    params=_params,
                )
                request = _convert_request(request)
                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)  # type: ignore

                path_format_arguments = {
                    "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
                }
                request.method = "GET"
            return request

        async def extract_data(pipeline_response):
            deserialized = self._deserialize("GetDocumentModelsResponse", pipeline_response)
            list_of_elem = deserialized.value
            if cls:
                list_of_elem = cls(list_of_elem)
            return deserialized.next_link or None, AsyncList(list_of_elem)

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

            pipeline_response = await self._client._pipeline.run(  # pylint: disable=protected-access
                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)
                error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
                raise HttpResponseError(response=response, model=error)

            return pipeline_response


        return AsyncItemPaged(
            get_next, extract_data
        )
    get_document_models.metadata = {'url': "/documentModels"}  # type: ignore

    @distributed_trace_async
    async def get_document_model(
        self,
        model_id: str,
        **kwargs: Any
    ) -> _models.DocumentModelDetails:
        """Get document model.

        Gets detailed document model information.

        :param model_id: Unique document model name.
        :type model_id: str
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: DocumentModelDetails, or the result of cls(response)
        :rtype: ~azure.ai.formrecognizer.v2022_08_31.models.DocumentModelDetails
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}) or {})

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

        api_version = kwargs.pop('api_version', _params.pop('api-version', "2022-08-31"))  # type: str
        cls = kwargs.pop('cls', None)  # type: ClsType[_models.DocumentModelDetails]

        
        request = build_get_document_model_request(
            model_id=model_id,
            api_version=api_version,
            template_url=self.get_document_model.metadata['url'],
            headers=_headers,
            params=_params,
        )
        request = _convert_request(request)
        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)  # type: ignore

        pipeline_response = await self._client._pipeline.run(  # type: ignore # pylint: disable=protected-access
            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)
            error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
            raise HttpResponseError(response=response, model=error)

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

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

        return deserialized

    get_document_model.metadata = {'url': "/documentModels/{modelId}"}  # type: ignore


    @distributed_trace_async
    async def delete_document_model(  # pylint: disable=inconsistent-return-statements
        self,
        model_id: str,
        **kwargs: Any
    ) -> None:
        """Delete document model.

        Deletes document model.

        :param model_id: Unique document model name.
        :type model_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
        """
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}) or {})

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

        api_version = kwargs.pop('api_version', _params.pop('api-version', "2022-08-31"))  # type: str
        cls = kwargs.pop('cls', None)  # type: ClsType[None]

        
        request = build_delete_document_model_request(
            model_id=model_id,
            api_version=api_version,
            template_url=self.delete_document_model.metadata['url'],
            headers=_headers,
            params=_params,
        )
        request = _convert_request(request)
        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)  # type: ignore

        pipeline_response = await self._client._pipeline.run(  # type: ignore # pylint: disable=protected-access
            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)
            error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
            raise HttpResponseError(response=response, model=error)

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

    delete_document_model.metadata = {'url': "/documentModels/{modelId}"}  # type: ignore


    @distributed_trace_async
    async def get_resource_details(
        self,
        **kwargs: Any
    ) -> _models.ResourceDetails:
        """Get resource info.

        Return information about the current resource.

        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: ResourceDetails, or the result of cls(response)
        :rtype: ~azure.ai.formrecognizer.v2022_08_31.models.ResourceDetails
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}) or {})

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

        api_version = kwargs.pop('api_version', _params.pop('api-version', "2022-08-31"))  # type: str
        cls = kwargs.pop('cls', None)  # type: ClsType[_models.ResourceDetails]

        
        request = build_get_resource_details_request(
            api_version=api_version,
            template_url=self.get_resource_details.metadata['url'],
            headers=_headers,
            params=_params,
        )
        request = _convert_request(request)
        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)  # type: ignore

        pipeline_response = await self._client._pipeline.run(  # type: ignore # pylint: disable=protected-access
            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)
            error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
            raise HttpResponseError(response=response, model=error)

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

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

        return deserialized

    get_resource_details.metadata = {'url': "/info"}  # type: ignore

