# pylint: disable=too-many-lines,too-many-statements
# 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) Python Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from io import IOBase
import json
import sys
from typing import Any, Callable, Dict, IO, Iterable, Iterator, List, Optional, Type, TypeVar, Union, cast, overload
import urllib.parse

from azure.core.exceptions import (
    ClientAuthenticationError,
    HttpResponseError,
    ResourceExistsError,
    ResourceNotFoundError,
    ResourceNotModifiedError,
    map_error,
)
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.polling import LROPoller, NoPolling, PollingMethod
from azure.core.polling.base_polling import LROBasePolling
from azure.core.rest import HttpRequest, HttpResponse
from azure.core.tracing.decorator import distributed_trace
from azure.core.utils import case_insensitive_dict

from .. import models as _models
from .._model_base import SdkJSONEncoder, _deserialize
from .._serialization import Serializer
from .._vendor import DeidentificationClientMixinABC

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

_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False


def build_deidentification_get_job_request(name: str, **kwargs: Any) -> HttpRequest:
    _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
    _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

    api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-07-12-preview"))
    accept = _headers.pop("Accept", "application/json")

    # Construct URL
    _url = "/jobs/{name}"
    path_format_arguments = {
        "name": _SERIALIZER.url("name", name, "str"),
    }

    _url: str = _url.format(**path_format_arguments)  # type: ignore

    # Construct parameters
    _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")

    # Construct headers
    _headers["Accept"] = _SERIALIZER.header("accept", accept, "str")

    return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)


def build_deidentification_create_job_request(name: str, **kwargs: Any) -> HttpRequest:  # pylint: disable=name-too-long
    _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
    _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

    content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
    api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-07-12-preview"))
    accept = _headers.pop("Accept", "application/json")

    # Construct URL
    _url = "/jobs/{name}"
    path_format_arguments = {
        "name": _SERIALIZER.url("name", name, "str"),
    }

    _url: str = _url.format(**path_format_arguments)  # type: ignore

    # Construct parameters
    _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")

    # Construct headers
    if content_type is not None:
        _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
    _headers["Accept"] = _SERIALIZER.header("accept", accept, "str")

    return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs)


def build_deidentification_list_jobs_request(
    *, maxpagesize: Optional[int] = None, continuation_token_parameter: Optional[str] = None, **kwargs: Any
) -> HttpRequest:
    _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
    _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

    api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-07-12-preview"))
    accept = _headers.pop("Accept", "application/json")

    # Construct URL
    _url = "/jobs"

    # Construct parameters
    _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
    if maxpagesize is not None:
        _params["maxpagesize"] = _SERIALIZER.query("maxpagesize", maxpagesize, "int")
    if continuation_token_parameter is not None:
        _params["continuationToken"] = _SERIALIZER.query(
            "continuation_token_parameter", continuation_token_parameter, "str"
        )

    # Construct headers
    _headers["Accept"] = _SERIALIZER.header("accept", accept, "str")

    return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)


def build_deidentification_list_job_documents_request(  # pylint: disable=name-too-long
    name: str, *, maxpagesize: Optional[int] = None, continuation_token_parameter: Optional[str] = None, **kwargs: Any
) -> HttpRequest:
    _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
    _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

    api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-07-12-preview"))
    accept = _headers.pop("Accept", "application/json")

    # Construct URL
    _url = "/jobs/{name}/documents"
    path_format_arguments = {
        "name": _SERIALIZER.url("name", name, "str"),
    }

    _url: str = _url.format(**path_format_arguments)  # type: ignore

    # Construct parameters
    _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
    if maxpagesize is not None:
        _params["maxpagesize"] = _SERIALIZER.query("maxpagesize", maxpagesize, "int")
    if continuation_token_parameter is not None:
        _params["continuationToken"] = _SERIALIZER.query(
            "continuation_token_parameter", continuation_token_parameter, "str"
        )

    # Construct headers
    _headers["Accept"] = _SERIALIZER.header("accept", accept, "str")

    return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs)


def build_deidentification_cancel_job_request(name: str, **kwargs: Any) -> HttpRequest:  # pylint: disable=name-too-long
    _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
    _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

    api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-07-12-preview"))
    accept = _headers.pop("Accept", "application/json")

    # Construct URL
    _url = "/jobs/{name}:cancel"
    path_format_arguments = {
        "name": _SERIALIZER.url("name", name, "str"),
    }

    _url: str = _url.format(**path_format_arguments)  # type: ignore

    # Construct parameters
    _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")

    # Construct headers
    _headers["Accept"] = _SERIALIZER.header("accept", accept, "str")

    return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs)


def build_deidentification_delete_job_request(name: str, **kwargs: Any) -> HttpRequest:  # pylint: disable=name-too-long
    _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
    _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

    api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-07-12-preview"))
    accept = _headers.pop("Accept", "application/json")

    # Construct URL
    _url = "/jobs/{name}"
    path_format_arguments = {
        "name": _SERIALIZER.url("name", name, "str"),
    }

    _url: str = _url.format(**path_format_arguments)  # type: ignore

    # Construct parameters
    _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")

    # Construct headers
    _headers["Accept"] = _SERIALIZER.header("accept", accept, "str")

    return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs)


def build_deidentification_deidentify_request(**kwargs: Any) -> HttpRequest:  # pylint: disable=name-too-long
    _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
    _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

    content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
    api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-07-12-preview"))
    accept = _headers.pop("Accept", "application/json")

    # Construct URL
    _url = "/deid"

    # Construct parameters
    _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")

    # Construct headers
    if content_type is not None:
        _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
    _headers["Accept"] = _SERIALIZER.header("accept", accept, "str")

    return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs)


class DeidentificationClientOperationsMixin(DeidentificationClientMixinABC):

    @distributed_trace
    def get_job(self, name: str, **kwargs: Any) -> _models.DeidentificationJob:
        """Get a de-identification job.

        Resource read operation template.

        :param name: The name of a job. Required.
        :type name: str
        :return: DeidentificationJob. The DeidentificationJob is compatible with MutableMapping
        :rtype: ~azure.health.deidentification.models.DeidentificationJob
        :raises ~azure.core.exceptions.HttpResponseError:

        Example:
            .. code-block:: python

                # response body for status code(s): 200
                response == {
                    "createdAt": "2020-02-20 00:00:00",
                    "lastUpdatedAt": "2020-02-20 00:00:00",
                    "name": "str",
                    "sourceLocation": {
                        "location": "str",
                        "prefix": "str",
                        "extensions": [
                            "str"
                        ]
                    },
                    "status": "str",
                    "targetLocation": {
                        "location": "str",
                        "prefix": "str"
                    },
                    "dataType": "str",
                    "error": {
                        "code": "str",
                        "message": "str",
                        "details": [
                            ...
                        ],
                        "innererror": {
                            "code": "str",
                            "innererror": ...
                        },
                        "target": "str"
                    },
                    "operation": "str",
                    "redactionFormat": "str",
                    "startedAt": "2020-02-20 00:00:00",
                    "summary": {
                        "bytesProcessed": 0,
                        "canceled": 0,
                        "failed": 0,
                        "successful": 0,
                        "total": 0
                    }
                }
        """
        error_map: MutableMapping[int, Type[HttpResponseError]] = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

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

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

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

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

        response = pipeline_response.http_response

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

        response_headers = {}
        response_headers["x-ms-client-request-id"] = self._deserialize(
            "str", response.headers.get("x-ms-client-request-id")
        )

        if _stream:
            deserialized = response.iter_bytes()
        else:
            deserialized = _deserialize(_models.DeidentificationJob, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    def _create_job_initial(
        self, name: str, resource: Union[_models.DeidentificationJob, JSON, IO[bytes]], **kwargs: Any
    ) -> Iterator[bytes]:
        error_map: MutableMapping[int, Type[HttpResponseError]] = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

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

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

        content_type = content_type or "application/json"
        _content = None
        if isinstance(resource, (IOBase, bytes)):
            _content = resource
        else:
            _content = json.dumps(resource, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

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

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

        response = pipeline_response.http_response

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

        response_headers = {}
        if response.status_code == 200:
            response_headers["x-ms-client-request-id"] = self._deserialize(
                "str", response.headers.get("x-ms-client-request-id")
            )
            response_headers["Operation-Location"] = self._deserialize(
                "str", response.headers.get("Operation-Location")
            )

            deserialized = response.iter_bytes()

        if response.status_code == 201:
            response_headers["x-ms-client-request-id"] = self._deserialize(
                "str", response.headers.get("x-ms-client-request-id")
            )
            response_headers["Operation-Location"] = self._deserialize(
                "str", response.headers.get("Operation-Location")
            )

            deserialized = response.iter_bytes()

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @overload
    def begin_create_job(
        self, name: str, resource: _models.DeidentificationJob, *, content_type: str = "application/json", **kwargs: Any
    ) -> LROPoller[_models.DeidentificationJob]:
        """Create a de-identification job.

        Long-running resource create or replace operation template.

        :param name: The name of a job. Required.
        :type name: str
        :param resource: The resource instance. Required.
        :type resource: ~azure.health.deidentification.models.DeidentificationJob
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of LROPoller that returns DeidentificationJob. The DeidentificationJob is
         compatible with MutableMapping
        :rtype:
         ~azure.core.polling.LROPoller[~azure.health.deidentification.models.DeidentificationJob]
        :raises ~azure.core.exceptions.HttpResponseError:

        Example:
            .. code-block:: python

                # JSON input template you can fill out and use as your body input.
                resource = {
                    "createdAt": "2020-02-20 00:00:00",
                    "lastUpdatedAt": "2020-02-20 00:00:00",
                    "name": "str",
                    "sourceLocation": {
                        "location": "str",
                        "prefix": "str",
                        "extensions": [
                            "str"
                        ]
                    },
                    "status": "str",
                    "targetLocation": {
                        "location": "str",
                        "prefix": "str"
                    },
                    "dataType": "str",
                    "error": {
                        "code": "str",
                        "message": "str",
                        "details": [
                            ...
                        ],
                        "innererror": {
                            "code": "str",
                            "innererror": ...
                        },
                        "target": "str"
                    },
                    "operation": "str",
                    "redactionFormat": "str",
                    "startedAt": "2020-02-20 00:00:00",
                    "summary": {
                        "bytesProcessed": 0,
                        "canceled": 0,
                        "failed": 0,
                        "successful": 0,
                        "total": 0
                    }
                }

                # response body for status code(s): 201, 200
                response == {
                    "createdAt": "2020-02-20 00:00:00",
                    "lastUpdatedAt": "2020-02-20 00:00:00",
                    "name": "str",
                    "sourceLocation": {
                        "location": "str",
                        "prefix": "str",
                        "extensions": [
                            "str"
                        ]
                    },
                    "status": "str",
                    "targetLocation": {
                        "location": "str",
                        "prefix": "str"
                    },
                    "dataType": "str",
                    "error": {
                        "code": "str",
                        "message": "str",
                        "details": [
                            ...
                        ],
                        "innererror": {
                            "code": "str",
                            "innererror": ...
                        },
                        "target": "str"
                    },
                    "operation": "str",
                    "redactionFormat": "str",
                    "startedAt": "2020-02-20 00:00:00",
                    "summary": {
                        "bytesProcessed": 0,
                        "canceled": 0,
                        "failed": 0,
                        "successful": 0,
                        "total": 0
                    }
                }
        """

    @overload
    def begin_create_job(
        self, name: str, resource: JSON, *, content_type: str = "application/json", **kwargs: Any
    ) -> LROPoller[_models.DeidentificationJob]:
        """Create a de-identification job.

        Long-running resource create or replace operation template.

        :param name: The name of a job. Required.
        :type name: str
        :param resource: The resource instance. Required.
        :type resource: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of LROPoller that returns DeidentificationJob. The DeidentificationJob is
         compatible with MutableMapping
        :rtype:
         ~azure.core.polling.LROPoller[~azure.health.deidentification.models.DeidentificationJob]
        :raises ~azure.core.exceptions.HttpResponseError:

        Example:
            .. code-block:: python

                # response body for status code(s): 201, 200
                response == {
                    "createdAt": "2020-02-20 00:00:00",
                    "lastUpdatedAt": "2020-02-20 00:00:00",
                    "name": "str",
                    "sourceLocation": {
                        "location": "str",
                        "prefix": "str",
                        "extensions": [
                            "str"
                        ]
                    },
                    "status": "str",
                    "targetLocation": {
                        "location": "str",
                        "prefix": "str"
                    },
                    "dataType": "str",
                    "error": {
                        "code": "str",
                        "message": "str",
                        "details": [
                            ...
                        ],
                        "innererror": {
                            "code": "str",
                            "innererror": ...
                        },
                        "target": "str"
                    },
                    "operation": "str",
                    "redactionFormat": "str",
                    "startedAt": "2020-02-20 00:00:00",
                    "summary": {
                        "bytesProcessed": 0,
                        "canceled": 0,
                        "failed": 0,
                        "successful": 0,
                        "total": 0
                    }
                }
        """

    @overload
    def begin_create_job(
        self, name: str, resource: IO[bytes], *, content_type: str = "application/json", **kwargs: Any
    ) -> LROPoller[_models.DeidentificationJob]:
        """Create a de-identification job.

        Long-running resource create or replace operation template.

        :param name: The name of a job. Required.
        :type name: str
        :param resource: The resource instance. Required.
        :type resource: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of LROPoller that returns DeidentificationJob. The DeidentificationJob is
         compatible with MutableMapping
        :rtype:
         ~azure.core.polling.LROPoller[~azure.health.deidentification.models.DeidentificationJob]
        :raises ~azure.core.exceptions.HttpResponseError:

        Example:
            .. code-block:: python

                # response body for status code(s): 201, 200
                response == {
                    "createdAt": "2020-02-20 00:00:00",
                    "lastUpdatedAt": "2020-02-20 00:00:00",
                    "name": "str",
                    "sourceLocation": {
                        "location": "str",
                        "prefix": "str",
                        "extensions": [
                            "str"
                        ]
                    },
                    "status": "str",
                    "targetLocation": {
                        "location": "str",
                        "prefix": "str"
                    },
                    "dataType": "str",
                    "error": {
                        "code": "str",
                        "message": "str",
                        "details": [
                            ...
                        ],
                        "innererror": {
                            "code": "str",
                            "innererror": ...
                        },
                        "target": "str"
                    },
                    "operation": "str",
                    "redactionFormat": "str",
                    "startedAt": "2020-02-20 00:00:00",
                    "summary": {
                        "bytesProcessed": 0,
                        "canceled": 0,
                        "failed": 0,
                        "successful": 0,
                        "total": 0
                    }
                }
        """

    @distributed_trace
    def begin_create_job(
        self, name: str, resource: Union[_models.DeidentificationJob, JSON, IO[bytes]], **kwargs: Any
    ) -> LROPoller[_models.DeidentificationJob]:
        """Create a de-identification job.

        Long-running resource create or replace operation template.

        :param name: The name of a job. Required.
        :type name: str
        :param resource: The resource instance. Is one of the following types: DeidentificationJob,
         JSON, IO[bytes] Required.
        :type resource: ~azure.health.deidentification.models.DeidentificationJob or JSON or IO[bytes]
        :return: An instance of LROPoller that returns DeidentificationJob. The DeidentificationJob is
         compatible with MutableMapping
        :rtype:
         ~azure.core.polling.LROPoller[~azure.health.deidentification.models.DeidentificationJob]
        :raises ~azure.core.exceptions.HttpResponseError:

        Example:
            .. code-block:: python

                # JSON input template you can fill out and use as your body input.
                resource = {
                    "createdAt": "2020-02-20 00:00:00",
                    "lastUpdatedAt": "2020-02-20 00:00:00",
                    "name": "str",
                    "sourceLocation": {
                        "location": "str",
                        "prefix": "str",
                        "extensions": [
                            "str"
                        ]
                    },
                    "status": "str",
                    "targetLocation": {
                        "location": "str",
                        "prefix": "str"
                    },
                    "dataType": "str",
                    "error": {
                        "code": "str",
                        "message": "str",
                        "details": [
                            ...
                        ],
                        "innererror": {
                            "code": "str",
                            "innererror": ...
                        },
                        "target": "str"
                    },
                    "operation": "str",
                    "redactionFormat": "str",
                    "startedAt": "2020-02-20 00:00:00",
                    "summary": {
                        "bytesProcessed": 0,
                        "canceled": 0,
                        "failed": 0,
                        "successful": 0,
                        "total": 0
                    }
                }

                # response body for status code(s): 201, 200
                response == {
                    "createdAt": "2020-02-20 00:00:00",
                    "lastUpdatedAt": "2020-02-20 00:00:00",
                    "name": "str",
                    "sourceLocation": {
                        "location": "str",
                        "prefix": "str",
                        "extensions": [
                            "str"
                        ]
                    },
                    "status": "str",
                    "targetLocation": {
                        "location": "str",
                        "prefix": "str"
                    },
                    "dataType": "str",
                    "error": {
                        "code": "str",
                        "message": "str",
                        "details": [
                            ...
                        ],
                        "innererror": {
                            "code": "str",
                            "innererror": ...
                        },
                        "target": "str"
                    },
                    "operation": "str",
                    "redactionFormat": "str",
                    "startedAt": "2020-02-20 00:00:00",
                    "summary": {
                        "bytesProcessed": 0,
                        "canceled": 0,
                        "failed": 0,
                        "successful": 0,
                        "total": 0
                    }
                }
        """
        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[_models.DeidentificationJob] = kwargs.pop("cls", None)
        polling: Union[bool, PollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = self._create_job_initial(
                name=name,
                resource=resource,
                content_type=content_type,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):
            response_headers = {}
            response = pipeline_response.http_response
            response_headers["x-ms-client-request-id"] = self._deserialize(
                "str", response.headers.get("x-ms-client-request-id")
            )
            response_headers["Operation-Location"] = self._deserialize(
                "str", response.headers.get("Operation-Location")
            )

            deserialized = _deserialize(_models.DeidentificationJob, response.json())
            if cls:
                return cls(pipeline_response, deserialized, response_headers)  # type: ignore
            return deserialized

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

        if polling is True:
            polling_method: PollingMethod = cast(
                PollingMethod, LROBasePolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs)
            )
        elif polling is False:
            polling_method = cast(PollingMethod, NoPolling())
        else:
            polling_method = polling
        if cont_token:
            return LROPoller[_models.DeidentificationJob].from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output,
            )
        return LROPoller[_models.DeidentificationJob](
            self._client, raw_result, get_long_running_output, polling_method  # type: ignore
        )

    @distributed_trace
    def list_jobs(
        self, *, continuation_token_parameter: Optional[str] = None, **kwargs: Any
    ) -> Iterable["_models.DeidentificationJob"]:
        """List de-identification jobs.

        Resource list operation template.

        :keyword continuation_token_parameter: Token to continue a previous query. Default value is
         None.
        :paramtype continuation_token_parameter: str
        :return: An iterator like instance of DeidentificationJob
        :rtype: ~azure.core.paging.ItemPaged[~azure.health.deidentification.models.DeidentificationJob]
        :raises ~azure.core.exceptions.HttpResponseError:

        Example:
            .. code-block:: python

                # response body for status code(s): 200
                response == {
                    "createdAt": "2020-02-20 00:00:00",
                    "lastUpdatedAt": "2020-02-20 00:00:00",
                    "name": "str",
                    "sourceLocation": {
                        "location": "str",
                        "prefix": "str",
                        "extensions": [
                            "str"
                        ]
                    },
                    "status": "str",
                    "targetLocation": {
                        "location": "str",
                        "prefix": "str"
                    },
                    "dataType": "str",
                    "error": {
                        "code": "str",
                        "message": "str",
                        "details": [
                            ...
                        ],
                        "innererror": {
                            "code": "str",
                            "innererror": ...
                        },
                        "target": "str"
                    },
                    "operation": "str",
                    "redactionFormat": "str",
                    "startedAt": "2020-02-20 00:00:00",
                    "summary": {
                        "bytesProcessed": 0,
                        "canceled": 0,
                        "failed": 0,
                        "successful": 0,
                        "total": 0
                    }
                }
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        maxpagesize = kwargs.pop("maxpagesize", None)
        cls: ClsType[List[_models.DeidentificationJob]] = kwargs.pop("cls", None)

        error_map: MutableMapping[int, Type[HttpResponseError]] = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

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

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

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

            return _request

        def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(List[_models.DeidentificationJob], deserialized["value"])
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, iter(list_of_elem)

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

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

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

            return pipeline_response

        return ItemPaged(get_next, extract_data)

    @distributed_trace
    def list_job_documents(
        self, name: str, *, continuation_token_parameter: Optional[str] = None, **kwargs: Any
    ) -> Iterable["_models.DocumentDetails"]:
        """List processed documents within a job.

        Resource list operation template.

        :param name: The name of a job. Required.
        :type name: str
        :keyword continuation_token_parameter: Token to continue a previous query. Default value is
         None.
        :paramtype continuation_token_parameter: str
        :return: An iterator like instance of DocumentDetails
        :rtype: ~azure.core.paging.ItemPaged[~azure.health.deidentification.models.DocumentDetails]
        :raises ~azure.core.exceptions.HttpResponseError:

        Example:
            .. code-block:: python

                # response body for status code(s): 200
                response == {
                    "id": "str",
                    "input": {
                        "etag": "str",
                        "path": "str"
                    },
                    "status": "str",
                    "error": {
                        "code": "str",
                        "message": "str",
                        "details": [
                            ...
                        ],
                        "innererror": {
                            "code": "str",
                            "innererror": ...
                        },
                        "target": "str"
                    },
                    "output": {
                        "etag": "str",
                        "path": "str"
                    }
                }
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        maxpagesize = kwargs.pop("maxpagesize", None)
        cls: ClsType[List[_models.DocumentDetails]] = kwargs.pop("cls", None)

        error_map: MutableMapping[int, Type[HttpResponseError]] = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

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

                _request = build_deidentification_list_job_documents_request(
                    name=name,
                    maxpagesize=maxpagesize,
                    continuation_token_parameter=continuation_token_parameter,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

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

            return _request

        def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(List[_models.DocumentDetails], deserialized["value"])
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") or None, iter(list_of_elem)

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

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

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

            return pipeline_response

        return ItemPaged(get_next, extract_data)

    @distributed_trace
    def cancel_job(self, name: str, **kwargs: Any) -> _models.DeidentificationJob:
        """Cancel a de-identification job.

        Cancels a job that is in progress.

        The job will be marked as canceled and the service will stop processing the job. The service
        will not delete any documents that have already been processed.

        If the job is already complete, this will have no effect.

        :param name: The name of a job. Required.
        :type name: str
        :return: DeidentificationJob. The DeidentificationJob is compatible with MutableMapping
        :rtype: ~azure.health.deidentification.models.DeidentificationJob
        :raises ~azure.core.exceptions.HttpResponseError:

        Example:
            .. code-block:: python

                # response body for status code(s): 200
                response == {
                    "createdAt": "2020-02-20 00:00:00",
                    "lastUpdatedAt": "2020-02-20 00:00:00",
                    "name": "str",
                    "sourceLocation": {
                        "location": "str",
                        "prefix": "str",
                        "extensions": [
                            "str"
                        ]
                    },
                    "status": "str",
                    "targetLocation": {
                        "location": "str",
                        "prefix": "str"
                    },
                    "dataType": "str",
                    "error": {
                        "code": "str",
                        "message": "str",
                        "details": [
                            ...
                        ],
                        "innererror": {
                            "code": "str",
                            "innererror": ...
                        },
                        "target": "str"
                    },
                    "operation": "str",
                    "redactionFormat": "str",
                    "startedAt": "2020-02-20 00:00:00",
                    "summary": {
                        "bytesProcessed": 0,
                        "canceled": 0,
                        "failed": 0,
                        "successful": 0,
                        "total": 0
                    }
                }
        """
        error_map: MutableMapping[int, Type[HttpResponseError]] = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

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

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

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

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

        response = pipeline_response.http_response

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

        response_headers = {}
        response_headers["x-ms-client-request-id"] = self._deserialize(
            "str", response.headers.get("x-ms-client-request-id")
        )

        if _stream:
            deserialized = response.iter_bytes()
        else:
            deserialized = _deserialize(_models.DeidentificationJob, response.json())

        if cls:
            return cls(pipeline_response, deserialized, response_headers)  # type: ignore

        return deserialized  # type: ignore

    @distributed_trace
    def delete_job(self, name: str, **kwargs: Any) -> None:  # pylint: disable=inconsistent-return-statements
        """Delete a de-identification job.

        Removes the record of the job from the service. Does not delete any documents.

        :param name: The name of a job. Required.
        :type name: str
        :return: None
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping[int, Type[HttpResponseError]] = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

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

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

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

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

        response = pipeline_response.http_response

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

        response_headers = {}
        response_headers["x-ms-client-request-id"] = self._deserialize(
            "str", response.headers.get("x-ms-client-request-id")
        )

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

    @overload
    def deidentify(
        self, body: _models.DeidentificationContent, *, content_type: str = "application/json", **kwargs: Any
    ) -> _models.DeidentificationResult:
        """De-identify text.

        A remote procedure call (RPC) operation.

        :param body: Request body for de-identification operation. Required.
        :type body: ~azure.health.deidentification.models.DeidentificationContent
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: DeidentificationResult. The DeidentificationResult is compatible with MutableMapping
        :rtype: ~azure.health.deidentification.models.DeidentificationResult
        :raises ~azure.core.exceptions.HttpResponseError:

        Example:
            .. code-block:: python

                # JSON input template you can fill out and use as your body input.
                body = {
                    "inputText": "str",
                    "dataType": "str",
                    "operation": "str",
                    "redactionFormat": "str"
                }

                # response body for status code(s): 200
                response == {
                    "outputText": "str",
                    "taggerResult": {
                        "entities": [
                            {
                                "category": "str",
                                "length": {
                                    "codePoint": 0,
                                    "utf16": 0,
                                    "utf8": 0
                                },
                                "offset": {
                                    "codePoint": 0,
                                    "utf16": 0,
                                    "utf8": 0
                                },
                                "confidenceScore": 0.0,
                                "text": "str"
                            }
                        ],
                        "etag": "str",
                        "path": "str"
                    }
                }
        """

    @overload
    def deidentify(
        self, body: JSON, *, content_type: str = "application/json", **kwargs: Any
    ) -> _models.DeidentificationResult:
        """De-identify text.

        A remote procedure call (RPC) operation.

        :param body: Request body for de-identification operation. Required.
        :type body: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: DeidentificationResult. The DeidentificationResult is compatible with MutableMapping
        :rtype: ~azure.health.deidentification.models.DeidentificationResult
        :raises ~azure.core.exceptions.HttpResponseError:

        Example:
            .. code-block:: python

                # response body for status code(s): 200
                response == {
                    "outputText": "str",
                    "taggerResult": {
                        "entities": [
                            {
                                "category": "str",
                                "length": {
                                    "codePoint": 0,
                                    "utf16": 0,
                                    "utf8": 0
                                },
                                "offset": {
                                    "codePoint": 0,
                                    "utf16": 0,
                                    "utf8": 0
                                },
                                "confidenceScore": 0.0,
                                "text": "str"
                            }
                        ],
                        "etag": "str",
                        "path": "str"
                    }
                }
        """

    @overload
    def deidentify(
        self, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any
    ) -> _models.DeidentificationResult:
        """De-identify text.

        A remote procedure call (RPC) operation.

        :param body: Request body for de-identification operation. Required.
        :type body: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: DeidentificationResult. The DeidentificationResult is compatible with MutableMapping
        :rtype: ~azure.health.deidentification.models.DeidentificationResult
        :raises ~azure.core.exceptions.HttpResponseError:

        Example:
            .. code-block:: python

                # response body for status code(s): 200
                response == {
                    "outputText": "str",
                    "taggerResult": {
                        "entities": [
                            {
                                "category": "str",
                                "length": {
                                    "codePoint": 0,
                                    "utf16": 0,
                                    "utf8": 0
                                },
                                "offset": {
                                    "codePoint": 0,
                                    "utf16": 0,
                                    "utf8": 0
                                },
                                "confidenceScore": 0.0,
                                "text": "str"
                            }
                        ],
                        "etag": "str",
                        "path": "str"
                    }
                }
        """

    @distributed_trace
    def deidentify(
        self, body: Union[_models.DeidentificationContent, JSON, IO[bytes]], **kwargs: Any
    ) -> _models.DeidentificationResult:
        """De-identify text.

        A remote procedure call (RPC) operation.

        :param body: Request body for de-identification operation. Is one of the following types:
         DeidentificationContent, JSON, IO[bytes] Required.
        :type body: ~azure.health.deidentification.models.DeidentificationContent or JSON or IO[bytes]
        :return: DeidentificationResult. The DeidentificationResult is compatible with MutableMapping
        :rtype: ~azure.health.deidentification.models.DeidentificationResult
        :raises ~azure.core.exceptions.HttpResponseError:

        Example:
            .. code-block:: python

                # JSON input template you can fill out and use as your body input.
                body = {
                    "inputText": "str",
                    "dataType": "str",
                    "operation": "str",
                    "redactionFormat": "str"
                }

                # response body for status code(s): 200
                response == {
                    "outputText": "str",
                    "taggerResult": {
                        "entities": [
                            {
                                "category": "str",
                                "length": {
                                    "codePoint": 0,
                                    "utf16": 0,
                                    "utf8": 0
                                },
                                "offset": {
                                    "codePoint": 0,
                                    "utf16": 0,
                                    "utf8": 0
                                },
                                "confidenceScore": 0.0,
                                "text": "str"
                            }
                        ],
                        "etag": "str",
                        "path": "str"
                    }
                }
        """
        error_map: MutableMapping[int, Type[HttpResponseError]] = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

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

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

        content_type = content_type or "application/json"
        _content = None
        if isinstance(body, (IOBase, bytes)):
            _content = body
        else:
            _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True)  # type: ignore

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

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

        response = pipeline_response.http_response

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

        if _stream:
            deserialized = response.iter_bytes()
        else:
            deserialized = _deserialize(_models.DeidentificationResult, response.json())

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

        return deserialized  # type: ignore
