# 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_model_request, build_get_analyze_document_result_request, build_get_info_request, build_get_model_request, build_get_models_request, build_get_operation_request, build_get_operations_request
T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]

class FormRecognizerClientOperationsMixin:

    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, str, _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-06-30-preview"))  # 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']:
            _json = analyze_request
        elif content_type.split(";")[0] in ['application/octet-stream', 'application/pdf', 'application/vnd.openxmlformats-officedocument.presentationml.presentation', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'image/bmp', 'image/heif', 'image/jpeg', 'image/png', 'image/tiff', 'text/html']:
            _content = analyze_request
        else:
            raise ValueError(
                "The content_type '{}' is not one of the allowed values: "
                "['application/octet-stream', 'application/pdf', 'application/vnd.openxmlformats-officedocument.presentationml.presentation', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'image/bmp', 'image/heif', 'image/jpeg', 'image/png', 'image/tiff', 'text/html', '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, str, _models.AnalyzeDocumentRequest]] = None,
        *,
        content_type: Optional[Union[str, "_models.ContentType"]] = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[None]:
        """Analyze document.

        Analyzes document with model.

        :param model_id: Unique 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_06_30_preview.models.StringIndexType
        :param analyze_request: Analyze request parameters. Default value is None.
        :type analyze_request: IO or str or
         ~azure.ai.formrecognizer.v2022_06_30_preview.models.AnalyzeDocumentRequest
        :keyword content_type: Media type of the body sent to the API. Known values are:
         "application/octet-stream", "application/pdf",
         "application/vnd.openxmlformats-officedocument.presentationml.presentation",
         "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
         "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "image/bmp",
         "image/heif", "image/jpeg", "image/png", "image/tiff", "text/html", and "application/json".
         Default value is "application/json".
        :paramtype content_type: str or ~azure.ai.formrecognizer.v2022_06_30_preview.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-06-30-preview"))  # 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 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_06_30_preview.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-06-30-preview"))  # 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-06-30-preview"))  # 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 model.

        Builds a custom document analysis model.

        :param build_request: Building request parameters.
        :type build_request:
         ~azure.ai.formrecognizer.v2022_06_30_preview.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-06-30-preview"))  # 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-06-30-preview"))  # 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 model.

        Creates a new model from document types of existing models.

        :param compose_request: Compose request parameters.
        :type compose_request:
         ~azure.ai.formrecognizer.v2022_06_30_preview.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-06-30-preview"))  # 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 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_06_30_preview.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_06_30_preview.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-06-30-preview"))  # 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-06-30-preview"))  # 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 model.

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

        :param model_id: Unique model name.
        :type model_id: str
        :param copy_to_request: Copy to request parameters.
        :type copy_to_request: ~azure.ai.formrecognizer.v2022_06_30_preview.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-06-30-preview"))  # 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_06_30_preview.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-06-30-preview"))  # 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.GetOperationResponse:
        """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: GetOperationResponse, or the result of cls(response)
        :rtype: ~azure.ai.formrecognizer.v2022_06_30_preview.models.GetOperationResponse
        :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-06-30-preview"))  # type: str
        cls = kwargs.pop('cls', None)  # type: ClsType[_models.GetOperationResponse]

        
        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('GetOperationResponse', pipeline_response)

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

        return deserialized

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


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

        List all models.

        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: An iterator like instance of either GetModelsResponse or the result of cls(response)
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.ai.formrecognizer.v2022_06_30_preview.models.GetModelsResponse]
        :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-06-30-preview"))  # type: str
        cls = kwargs.pop('cls', None)  # type: ClsType[_models.GetModelsResponse]

        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_models_request(
                    api_version=api_version,
                    template_url=self.get_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_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("GetModelsResponse", 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_models.metadata = {'url': "/documentModels"}  # type: ignore

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

        Gets detailed model information.

        :param model_id: Unique model name.
        :type model_id: str
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: ModelInfo, or the result of cls(response)
        :rtype: ~azure.ai.formrecognizer.v2022_06_30_preview.models.ModelInfo
        :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-06-30-preview"))  # type: str
        cls = kwargs.pop('cls', None)  # type: ClsType[_models.ModelInfo]

        
        request = build_get_model_request(
            model_id=model_id,
            api_version=api_version,
            template_url=self.get_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('ModelInfo', pipeline_response)

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

        return deserialized

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


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

        Deletes model.

        :param model_id: Unique 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-06-30-preview"))  # type: str
        cls = kwargs.pop('cls', None)  # type: ClsType[None]

        
        request = build_delete_model_request(
            model_id=model_id,
            api_version=api_version,
            template_url=self.delete_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_model.metadata = {'url': "/documentModels/{modelId}"}  # type: ignore


    @distributed_trace_async
    async def get_info(
        self,
        **kwargs: Any
    ) -> _models.GetInfoResponse:
        """Get info.

        Return basic info about the current resource.

        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: GetInfoResponse, or the result of cls(response)
        :rtype: ~azure.ai.formrecognizer.v2022_06_30_preview.models.GetInfoResponse
        :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-06-30-preview"))  # type: str
        cls = kwargs.pop('cls', None)  # type: ClsType[_models.GetInfoResponse]

        
        request = build_get_info_request(
            api_version=api_version,
            template_url=self.get_info.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('GetInfoResponse', pipeline_response)

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

        return deserialized

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

