# 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 collections.abc import MutableMapping
from io import IOBase
from typing import Any, Callable, Dict, IO, List, Optional, TypeVar, Union, overload
import urllib.parse

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

from ... import models as _models
from ..._utils.serialization import Deserializer, Serializer
from ...operations._digital_twins_operations import (
    build_add_relationship_request,
    build_add_request,
    build_delete_relationship_request,
    build_delete_request,
    build_get_by_id_request,
    build_get_component_request,
    build_get_relationship_by_id_request,
    build_list_incoming_relationships_request,
    build_list_relationships_request,
    build_send_component_telemetry_request,
    build_send_telemetry_request,
    build_update_component_request,
    build_update_relationship_request,
    build_update_request,
)
from .._configuration import AzureDigitalTwinsAPIConfiguration

JSON = MutableMapping[str, Any]
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]


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

        Instead, you should access the following operations through
        :class:`~azure.digitaltwins.core.aio.AzureDigitalTwinsAPI`'s
        :attr:`digital_twins` attribute.
    """

    models = _models

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

    @distributed_trace_async
    async def get_by_id(
        self,
        id: str,
        digital_twins_get_by_id_options: Optional[_models.DigitalTwinsGetByIdOptions] = None,
        **kwargs: Any
    ) -> Dict[str, Any]:
        """Retrieves a digital twin.
        Status codes:


        * 200 OK
        * 400 Bad Request

          * InvalidArgument - The digital twin id is invalid.

        * 404 Not Found

          * DigitalTwinNotFound - The digital twin was not found.

        :param id: The id of the digital twin. The id is unique within the service and case sensitive.
         Required.
        :type id: str
        :param digital_twins_get_by_id_options: Parameter group. Default value is None.
        :type digital_twins_get_by_id_options:
         ~azure.digitaltwins.core.models.DigitalTwinsGetByIdOptions
        :return: dict mapping str to any or the result of cls(response)
        :rtype: dict[str, any]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

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

        api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version))
        cls: ClsType[Dict[str, Any]] = kwargs.pop("cls", None)

        _traceparent = None
        _tracestate = None
        if digital_twins_get_by_id_options is not None:
            _traceparent = digital_twins_get_by_id_options.traceparent
            _tracestate = digital_twins_get_by_id_options.tracestate

        _request = build_get_by_id_request(
            id=id,
            traceparent=_traceparent,
            tracestate=_tracestate,
            api_version=api_version,
            headers=_headers,
            params=_params,
        )
        _request.url = self._client.format_url(_request.url)

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

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            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)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        deserialized = self._deserialize("{object}", pipeline_response.http_response)

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

        return deserialized  # type: ignore

    @distributed_trace_async
    async def add(
        self,
        id: str,
        twin: JSON,
        digital_twins_add_options: Optional[_models.DigitalTwinsAddOptions] = None,
        **kwargs: Any
    ) -> Dict[str, Any]:
        """Adds or replaces a digital twin.
        Status codes:


        * 200 OK
        * 400 Bad Request

          * InvalidArgument - The digital twin id or payload is invalid.
          * ModelDecommissioned - The model for the digital twin is decommissioned.
          * TwinLimitReached - The maximum number of digital twins allowed has been reached.
          * ValidationFailed - The digital twin payload is not valid.

        * 412 Precondition Failed

          * PreconditionFailed - The precondition check (If-Match or If-None-Match) failed.

        :param id: The id of the digital twin. The id is unique within the service and case sensitive.
         Required.
        :type id: str
        :param twin: The digital twin instance being added. If provided, the $dtId property is ignored.
         Required.
        :type twin: JSON
        :param digital_twins_add_options: Parameter group. Default value is None.
        :type digital_twins_add_options: ~azure.digitaltwins.core.models.DigitalTwinsAddOptions
        :return: dict mapping str to any or the result of cls(response)
        :rtype: dict[str, any]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            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 = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version))
        content_type: str = kwargs.pop("content_type", _headers.pop("Content-Type", "application/json"))
        cls: ClsType[Dict[str, Any]] = kwargs.pop("cls", None)

        _traceparent = None
        _tracestate = None
        _if_none_match = None
        if digital_twins_add_options is not None:
            _if_none_match = digital_twins_add_options.if_none_match
            _traceparent = digital_twins_add_options.traceparent
            _tracestate = digital_twins_add_options.tracestate
        _json = self._serialize.body(twin, "object")

        _request = build_add_request(
            id=id,
            traceparent=_traceparent,
            tracestate=_tracestate,
            if_none_match=_if_none_match,
            api_version=api_version,
            content_type=content_type,
            json=_json,
            headers=_headers,
            params=_params,
        )
        _request.url = self._client.format_url(_request.url)

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

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            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)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        deserialized = self._deserialize("{object}", pipeline_response.http_response)

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

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete(
        self, id: str, digital_twins_delete_options: Optional[_models.DigitalTwinsDeleteOptions] = None, **kwargs: Any
    ) -> None:
        """Deletes a digital twin. All relationships referencing the digital twin must already be deleted.
        Status codes:


        * 204 No Content
        * 400 Bad Request

          * InvalidArgument - The digital twin id is invalid.
          * RelationshipsNotDeleted - The digital twin contains relationships.

        * 404 Not Found

          * DigitalTwinNotFound - The digital twin was not found.

        * 412 Precondition Failed

          * PreconditionFailed - The precondition check (If-Match or If-None-Match) failed.

        :param id: The id of the digital twin. The id is unique within the service and case sensitive.
         Required.
        :type id: str
        :param digital_twins_delete_options: Parameter group. Default value is None.
        :type digital_twins_delete_options: ~azure.digitaltwins.core.models.DigitalTwinsDeleteOptions
        :return: None or the result of cls(response)
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

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

        api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version))
        cls: ClsType[None] = kwargs.pop("cls", None)

        _traceparent = None
        _tracestate = None
        _if_match = None
        if digital_twins_delete_options is not None:
            _if_match = digital_twins_delete_options.if_match
            _traceparent = digital_twins_delete_options.traceparent
            _tracestate = digital_twins_delete_options.tracestate

        _request = build_delete_request(
            id=id,
            traceparent=_traceparent,
            tracestate=_tracestate,
            if_match=_if_match,
            api_version=api_version,
            headers=_headers,
            params=_params,
        )
        _request.url = self._client.format_url(_request.url)

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

        response = pipeline_response.http_response

        if response.status_code not in [204]:
            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, {})  # type: ignore

    @overload
    async def update(
        self,
        id: str,
        patch_document: List[JSON],
        digital_twins_update_options: Optional[_models.DigitalTwinsUpdateOptions] = None,
        *,
        content_type: str = "application/json-patch+json",
        **kwargs: Any
    ) -> None:
        """Updates a digital twin.
        Status codes:


        * 204 No Content
        * 400 Bad Request

          * InvalidArgument - The digital twin id or payload is invalid.
          * JsonPatchInvalid - The JSON Patch provided is invalid.
          * ValidationFailed - Applying the patch results in an invalid digital twin.

        * 404 Not Found

          * DigitalTwinNotFound - The digital twin was not found.

        * 412 Precondition Failed

          * PreconditionFailed - The precondition check (If-Match or If-None-Match) failed.

        :param id: The id of the digital twin. The id is unique within the service and case sensitive.
         Required.
        :type id: str
        :param patch_document: An update specification described by JSON Patch. Updates to property
         values and $model elements may happen in the same request. Operations are limited to add,
         replace and remove. Required.
        :type patch_document: list[JSON]
        :param digital_twins_update_options: Parameter group. Default value is None.
        :type digital_twins_update_options: ~azure.digitaltwins.core.models.DigitalTwinsUpdateOptions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json-patch+json".
        :paramtype content_type: str
        :return: None or the result of cls(response)
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        id: str,
        patch_document: IO[bytes],
        digital_twins_update_options: Optional[_models.DigitalTwinsUpdateOptions] = None,
        *,
        content_type: str = "application/json-patch+json",
        **kwargs: Any
    ) -> None:
        """Updates a digital twin.
        Status codes:


        * 204 No Content
        * 400 Bad Request

          * InvalidArgument - The digital twin id or payload is invalid.
          * JsonPatchInvalid - The JSON Patch provided is invalid.
          * ValidationFailed - Applying the patch results in an invalid digital twin.

        * 404 Not Found

          * DigitalTwinNotFound - The digital twin was not found.

        * 412 Precondition Failed

          * PreconditionFailed - The precondition check (If-Match or If-None-Match) failed.

        :param id: The id of the digital twin. The id is unique within the service and case sensitive.
         Required.
        :type id: str
        :param patch_document: An update specification described by JSON Patch. Updates to property
         values and $model elements may happen in the same request. Operations are limited to add,
         replace and remove. Required.
        :type patch_document: IO[bytes]
        :param digital_twins_update_options: Parameter group. Default value is None.
        :type digital_twins_update_options: ~azure.digitaltwins.core.models.DigitalTwinsUpdateOptions
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json-patch+json".
        :paramtype content_type: str
        :return: None or the result of cls(response)
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def update(
        self,
        id: str,
        patch_document: Union[List[JSON], IO[bytes]],
        digital_twins_update_options: Optional[_models.DigitalTwinsUpdateOptions] = None,
        **kwargs: Any
    ) -> None:
        """Updates a digital twin.
        Status codes:


        * 204 No Content
        * 400 Bad Request

          * InvalidArgument - The digital twin id or payload is invalid.
          * JsonPatchInvalid - The JSON Patch provided is invalid.
          * ValidationFailed - Applying the patch results in an invalid digital twin.

        * 404 Not Found

          * DigitalTwinNotFound - The digital twin was not found.

        * 412 Precondition Failed

          * PreconditionFailed - The precondition check (If-Match or If-None-Match) failed.

        :param id: The id of the digital twin. The id is unique within the service and case sensitive.
         Required.
        :type id: str
        :param patch_document: An update specification described by JSON Patch. Updates to property
         values and $model elements may happen in the same request. Operations are limited to add,
         replace and remove. Is either a [JSON] type or a IO[bytes] type. Required.
        :type patch_document: list[JSON] or IO[bytes]
        :param digital_twins_update_options: Parameter group. Default value is None.
        :type digital_twins_update_options: ~azure.digitaltwins.core.models.DigitalTwinsUpdateOptions
        :return: None or the result of cls(response)
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            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 = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version))
        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[None] = kwargs.pop("cls", None)

        _traceparent = None
        _tracestate = None
        _if_match = None
        if digital_twins_update_options is not None:
            _if_match = digital_twins_update_options.if_match
            _traceparent = digital_twins_update_options.traceparent
            _tracestate = digital_twins_update_options.tracestate
        content_type = content_type or "application/json-patch+json"
        _json = None
        _content = None
        if isinstance(patch_document, (IOBase, bytes)):
            _content = patch_document
        else:
            _json = self._serialize.body(patch_document, "[object]")

        _request = build_update_request(
            id=id,
            traceparent=_traceparent,
            tracestate=_tracestate,
            if_match=_if_match,
            api_version=api_version,
            content_type=content_type,
            json=_json,
            content=_content,
            headers=_headers,
            params=_params,
        )
        _request.url = self._client.format_url(_request.url)

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

        response = pipeline_response.http_response

        if response.status_code not in [204]:
            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)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

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

    @distributed_trace_async
    async def get_relationship_by_id(
        self,
        id: str,
        relationship_id: str,
        digital_twins_get_relationship_by_id_options: Optional[_models.DigitalTwinsGetRelationshipByIdOptions] = None,
        **kwargs: Any
    ) -> Dict[str, Any]:
        """Retrieves a relationship between two digital twins.
        Status codes:


        * 200 OK
        * 400 Bad Request

          * InvalidArgument - The digital twin id or relationship id is invalid.

        * 404 Not Found

          * DigitalTwinNotFound - The digital twin was not found.
          * RelationshipNotFound - The relationship was not found.

        :param id: The id of the digital twin. The id is unique within the service and case sensitive.
         Required.
        :type id: str
        :param relationship_id: The id of the relationship. The id is unique within the digital twin
         and case sensitive. Required.
        :type relationship_id: str
        :param digital_twins_get_relationship_by_id_options: Parameter group. Default value is None.
        :type digital_twins_get_relationship_by_id_options:
         ~azure.digitaltwins.core.models.DigitalTwinsGetRelationshipByIdOptions
        :return: dict mapping str to any or the result of cls(response)
        :rtype: dict[str, any]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

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

        api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version))
        cls: ClsType[Dict[str, Any]] = kwargs.pop("cls", None)

        _traceparent = None
        _tracestate = None
        if digital_twins_get_relationship_by_id_options is not None:
            _traceparent = digital_twins_get_relationship_by_id_options.traceparent
            _tracestate = digital_twins_get_relationship_by_id_options.tracestate

        _request = build_get_relationship_by_id_request(
            id=id,
            relationship_id=relationship_id,
            traceparent=_traceparent,
            tracestate=_tracestate,
            api_version=api_version,
            headers=_headers,
            params=_params,
        )
        _request.url = self._client.format_url(_request.url)

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

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            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)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        deserialized = self._deserialize("{object}", pipeline_response.http_response)

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

        return deserialized  # type: ignore

    @distributed_trace_async
    async def add_relationship(
        self,
        id: str,
        relationship_id: str,
        relationship: JSON,
        digital_twins_add_relationship_options: Optional[_models.DigitalTwinsAddRelationshipOptions] = None,
        **kwargs: Any
    ) -> Dict[str, Any]:
        """Adds a relationship between two digital twins.
        Status codes:


        * 200 OK
        * 400 Bad Request

          * InvalidArgument - The digital twin id, relationship id, or payload is invalid.
          * InvalidRelationship - The relationship is invalid.
          * OperationNotAllowed - The relationship cannot connect to the same digital twin.
          * ValidationFailed - The relationship content is invalid.

        * 404 Not Found

          * DigitalTwinNotFound - The digital twin was not found.
          * TargetTwinNotFound - The digital twin target of the relationship was not found.

        * 412 Precondition Failed

          * PreconditionFailed - The precondition check (If-Match or If-None-Match) failed.

        :param id: The id of the digital twin. The id is unique within the service and case sensitive.
         Required.
        :type id: str
        :param relationship_id: The id of the relationship. The id is unique within the digital twin
         and case sensitive. Required.
        :type relationship_id: str
        :param relationship: The data for the relationship. Required.
        :type relationship: JSON
        :param digital_twins_add_relationship_options: Parameter group. Default value is None.
        :type digital_twins_add_relationship_options:
         ~azure.digitaltwins.core.models.DigitalTwinsAddRelationshipOptions
        :return: dict mapping str to any or the result of cls(response)
        :rtype: dict[str, any]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            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 = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version))
        content_type: str = kwargs.pop("content_type", _headers.pop("Content-Type", "application/json"))
        cls: ClsType[Dict[str, Any]] = kwargs.pop("cls", None)

        _traceparent = None
        _tracestate = None
        _if_none_match = None
        if digital_twins_add_relationship_options is not None:
            _if_none_match = digital_twins_add_relationship_options.if_none_match
            _traceparent = digital_twins_add_relationship_options.traceparent
            _tracestate = digital_twins_add_relationship_options.tracestate
        _json = self._serialize.body(relationship, "object")

        _request = build_add_relationship_request(
            id=id,
            relationship_id=relationship_id,
            traceparent=_traceparent,
            tracestate=_tracestate,
            if_none_match=_if_none_match,
            api_version=api_version,
            content_type=content_type,
            json=_json,
            headers=_headers,
            params=_params,
        )
        _request.url = self._client.format_url(_request.url)

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

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            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)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        deserialized = self._deserialize("{object}", pipeline_response.http_response)

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

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete_relationship(
        self,
        id: str,
        relationship_id: str,
        digital_twins_delete_relationship_options: Optional[_models.DigitalTwinsDeleteRelationshipOptions] = None,
        **kwargs: Any
    ) -> None:
        """Deletes a relationship between two digital twins.
        Status codes:


        * 204 No Content
        * 400 Bad Request

          * InvalidArgument - The digital twin id or relationship id is invalid.

        * 404 Not Found

          * DigitalTwinNotFound - The digital twin was not found.
          * RelationshipNotFound - The relationship was not found.

        * 412 Precondition Failed

          * PreconditionFailed - The precondition check (If-Match or If-None-Match) failed.

        :param id: The id of the digital twin. The id is unique within the service and case sensitive.
         Required.
        :type id: str
        :param relationship_id: The id of the relationship. The id is unique within the digital twin
         and case sensitive. Required.
        :type relationship_id: str
        :param digital_twins_delete_relationship_options: Parameter group. Default value is None.
        :type digital_twins_delete_relationship_options:
         ~azure.digitaltwins.core.models.DigitalTwinsDeleteRelationshipOptions
        :return: None or the result of cls(response)
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

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

        api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version))
        cls: ClsType[None] = kwargs.pop("cls", None)

        _traceparent = None
        _tracestate = None
        _if_match = None
        if digital_twins_delete_relationship_options is not None:
            _if_match = digital_twins_delete_relationship_options.if_match
            _traceparent = digital_twins_delete_relationship_options.traceparent
            _tracestate = digital_twins_delete_relationship_options.tracestate

        _request = build_delete_relationship_request(
            id=id,
            relationship_id=relationship_id,
            traceparent=_traceparent,
            tracestate=_tracestate,
            if_match=_if_match,
            api_version=api_version,
            headers=_headers,
            params=_params,
        )
        _request.url = self._client.format_url(_request.url)

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

        response = pipeline_response.http_response

        if response.status_code not in [204]:
            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, {})  # type: ignore

    @overload
    async def update_relationship(
        self,
        id: str,
        relationship_id: str,
        patch_document: List[JSON],
        digital_twins_update_relationship_options: Optional[_models.DigitalTwinsUpdateRelationshipOptions] = None,
        *,
        content_type: str = "application/json-patch+json",
        **kwargs: Any
    ) -> None:
        """Updates the properties on a relationship between two digital twins.
        Status codes:


        * 204 No Content
        * 400 Bad Request

          * InvalidArgument - The digital twin id or relationship id is invalid.
          * InvalidRelationship - The relationship is invalid.
          * JsonPatchInvalid - The JSON Patch provided is invalid.
          * ValidationFailed - The relationship content is invalid.

        * 404 Not Found

          * DigitalTwinNotFound - The digital twin was not found.
          * RelationshipNotFound - The relationship was not found.

        * 409 Conflict

          * RelationshipAlreadyExists - The relationship already exists.

        * 412 Precondition Failed

          * PreconditionFailed - The precondition check (If-Match or If-None-Match) failed.

        :param id: The id of the digital twin. The id is unique within the service and case sensitive.
         Required.
        :type id: str
        :param relationship_id: The id of the relationship. The id is unique within the digital twin
         and case sensitive. Required.
        :type relationship_id: str
        :param patch_document: JSON Patch description of the update to the relationship properties.
         Required.
        :type patch_document: list[JSON]
        :param digital_twins_update_relationship_options: Parameter group. Default value is None.
        :type digital_twins_update_relationship_options:
         ~azure.digitaltwins.core.models.DigitalTwinsUpdateRelationshipOptions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json-patch+json".
        :paramtype content_type: str
        :return: None or the result of cls(response)
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update_relationship(
        self,
        id: str,
        relationship_id: str,
        patch_document: IO[bytes],
        digital_twins_update_relationship_options: Optional[_models.DigitalTwinsUpdateRelationshipOptions] = None,
        *,
        content_type: str = "application/json-patch+json",
        **kwargs: Any
    ) -> None:
        """Updates the properties on a relationship between two digital twins.
        Status codes:


        * 204 No Content
        * 400 Bad Request

          * InvalidArgument - The digital twin id or relationship id is invalid.
          * InvalidRelationship - The relationship is invalid.
          * JsonPatchInvalid - The JSON Patch provided is invalid.
          * ValidationFailed - The relationship content is invalid.

        * 404 Not Found

          * DigitalTwinNotFound - The digital twin was not found.
          * RelationshipNotFound - The relationship was not found.

        * 409 Conflict

          * RelationshipAlreadyExists - The relationship already exists.

        * 412 Precondition Failed

          * PreconditionFailed - The precondition check (If-Match or If-None-Match) failed.

        :param id: The id of the digital twin. The id is unique within the service and case sensitive.
         Required.
        :type id: str
        :param relationship_id: The id of the relationship. The id is unique within the digital twin
         and case sensitive. Required.
        :type relationship_id: str
        :param patch_document: JSON Patch description of the update to the relationship properties.
         Required.
        :type patch_document: IO[bytes]
        :param digital_twins_update_relationship_options: Parameter group. Default value is None.
        :type digital_twins_update_relationship_options:
         ~azure.digitaltwins.core.models.DigitalTwinsUpdateRelationshipOptions
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json-patch+json".
        :paramtype content_type: str
        :return: None or the result of cls(response)
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def update_relationship(
        self,
        id: str,
        relationship_id: str,
        patch_document: Union[List[JSON], IO[bytes]],
        digital_twins_update_relationship_options: Optional[_models.DigitalTwinsUpdateRelationshipOptions] = None,
        **kwargs: Any
    ) -> None:
        """Updates the properties on a relationship between two digital twins.
        Status codes:


        * 204 No Content
        * 400 Bad Request

          * InvalidArgument - The digital twin id or relationship id is invalid.
          * InvalidRelationship - The relationship is invalid.
          * JsonPatchInvalid - The JSON Patch provided is invalid.
          * ValidationFailed - The relationship content is invalid.

        * 404 Not Found

          * DigitalTwinNotFound - The digital twin was not found.
          * RelationshipNotFound - The relationship was not found.

        * 409 Conflict

          * RelationshipAlreadyExists - The relationship already exists.

        * 412 Precondition Failed

          * PreconditionFailed - The precondition check (If-Match or If-None-Match) failed.

        :param id: The id of the digital twin. The id is unique within the service and case sensitive.
         Required.
        :type id: str
        :param relationship_id: The id of the relationship. The id is unique within the digital twin
         and case sensitive. Required.
        :type relationship_id: str
        :param patch_document: JSON Patch description of the update to the relationship properties. Is
         either a [JSON] type or a IO[bytes] type. Required.
        :type patch_document: list[JSON] or IO[bytes]
        :param digital_twins_update_relationship_options: Parameter group. Default value is None.
        :type digital_twins_update_relationship_options:
         ~azure.digitaltwins.core.models.DigitalTwinsUpdateRelationshipOptions
        :return: None or the result of cls(response)
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            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 = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version))
        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[None] = kwargs.pop("cls", None)

        _traceparent = None
        _tracestate = None
        _if_match = None
        if digital_twins_update_relationship_options is not None:
            _if_match = digital_twins_update_relationship_options.if_match
            _traceparent = digital_twins_update_relationship_options.traceparent
            _tracestate = digital_twins_update_relationship_options.tracestate
        content_type = content_type or "application/json-patch+json"
        _json = None
        _content = None
        if isinstance(patch_document, (IOBase, bytes)):
            _content = patch_document
        else:
            _json = self._serialize.body(patch_document, "[object]")

        _request = build_update_relationship_request(
            id=id,
            relationship_id=relationship_id,
            traceparent=_traceparent,
            tracestate=_tracestate,
            if_match=_if_match,
            api_version=api_version,
            content_type=content_type,
            json=_json,
            content=_content,
            headers=_headers,
            params=_params,
        )
        _request.url = self._client.format_url(_request.url)

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

        response = pipeline_response.http_response

        if response.status_code not in [204]:
            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)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

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

    @distributed_trace
    def list_relationships(
        self,
        id: str,
        relationship_name: Optional[str] = None,
        digital_twins_list_relationships_options: Optional[_models.DigitalTwinsListRelationshipsOptions] = None,
        **kwargs: Any
    ) -> AsyncItemPaged[JSON]:
        """Retrieves the relationships from a digital twin.
        Status codes:


        * 200 OK
        * 400 Bad Request

          * InvalidArgument - The digital twin id is invalid.

        * 404 Not Found

          * DigitalTwinNotFound - The digital twin was not found.

        :param id: The id of the digital twin. The id is unique within the service and case sensitive.
         Required.
        :type id: str
        :param relationship_name: The name of the relationship. Default value is None.
        :type relationship_name: str
        :param digital_twins_list_relationships_options: Parameter group. Default value is None.
        :type digital_twins_list_relationships_options:
         ~azure.digitaltwins.core.models.DigitalTwinsListRelationshipsOptions
        :return: An iterator like instance of either JSON or the result of cls(response)
        :rtype: ~azure.core.async_paging.AsyncItemPaged[JSON]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version))
        cls: ClsType[_models.RelationshipCollection] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            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:
                _traceparent = None
                _tracestate = None
                if digital_twins_list_relationships_options is not None:
                    _traceparent = digital_twins_list_relationships_options.traceparent
                    _tracestate = digital_twins_list_relationships_options.tracestate

                _request = build_list_relationships_request(
                    id=id,
                    traceparent=_traceparent,
                    tracestate=_tracestate,
                    relationship_name=relationship_name,
                    api_version=api_version,
                    headers=_headers,
                    params=_params,
                )
                _request.url = self._client.format_url(_request.url)

            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
                )
                _request.url = self._client.format_url(_request.url)
                _request.method = "GET"
            return _request

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

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

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

            if response.status_code not in [200]:
                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)

    @distributed_trace
    def list_incoming_relationships(
        self,
        id: str,
        digital_twins_list_incoming_relationships_options: Optional[
            _models.DigitalTwinsListIncomingRelationshipsOptions
        ] = None,
        **kwargs: Any
    ) -> AsyncItemPaged["_models.IncomingRelationship"]:
        """Retrieves all incoming relationship for a digital twin.
        Status codes:


        * 200 OK
        * 400 Bad Request

          * InvalidArgument - The digital twin id is invalid.

        * 404 Not Found

          * DigitalTwinNotFound - The digital twin was not found.

        :param id: The id of the digital twin. The id is unique within the service and case sensitive.
         Required.
        :type id: str
        :param digital_twins_list_incoming_relationships_options: Parameter group. Default value is
         None.
        :type digital_twins_list_incoming_relationships_options:
         ~azure.digitaltwins.core.models.DigitalTwinsListIncomingRelationshipsOptions
        :return: An iterator like instance of either IncomingRelationship or the result of
         cls(response)
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.digitaltwins.core.models.IncomingRelationship]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version))
        cls: ClsType[_models.IncomingRelationshipCollection] = kwargs.pop("cls", None)

        error_map: MutableMapping = {
            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:
                _traceparent = None
                _tracestate = None
                if digital_twins_list_incoming_relationships_options is not None:
                    _traceparent = digital_twins_list_incoming_relationships_options.traceparent
                    _tracestate = digital_twins_list_incoming_relationships_options.tracestate

                _request = build_list_incoming_relationships_request(
                    id=id,
                    traceparent=_traceparent,
                    tracestate=_tracestate,
                    api_version=api_version,
                    headers=_headers,
                    params=_params,
                )
                _request.url = self._client.format_url(_request.url)

            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
                )
                _request.url = self._client.format_url(_request.url)
                _request.method = "GET"
            return _request

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

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

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

            if response.status_code not in [200]:
                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)

    @distributed_trace_async
    async def send_telemetry(
        self,
        id: str,
        message_id: str,
        telemetry: JSON,
        telemetry_source_time: Optional[str] = None,
        digital_twins_send_telemetry_options: Optional[_models.DigitalTwinsSendTelemetryOptions] = None,
        **kwargs: Any
    ) -> None:
        """Sends telemetry on behalf of a digital twin.
        Status codes:


        * 204 No Content
        * 400 Bad Request

          * InvalidArgument - The digital twin id or message id is invalid.
          * ValidationFailed - The telemetry content is invalid.

        * 404 Not Found

          * DigitalTwinNotFound - The digital twin was not found.

        :param id: The id of the digital twin. The id is unique within the service and case sensitive.
         Required.
        :type id: str
        :param message_id: A unique message identifier (in the scope of the digital twin id) that is
         commonly used for de-duplicating messages. Required.
        :type message_id: str
        :param telemetry: The telemetry measurements to send from the digital twin. Required.
        :type telemetry: JSON
        :param telemetry_source_time: An RFC 3339 timestamp that identifies the time the telemetry was
         measured. Default value is None.
        :type telemetry_source_time: str
        :param digital_twins_send_telemetry_options: Parameter group. Default value is None.
        :type digital_twins_send_telemetry_options:
         ~azure.digitaltwins.core.models.DigitalTwinsSendTelemetryOptions
        :return: None or the result of cls(response)
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            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 = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version))
        content_type: str = kwargs.pop("content_type", _headers.pop("Content-Type", "application/json"))
        cls: ClsType[None] = kwargs.pop("cls", None)

        _traceparent = None
        _tracestate = None
        if digital_twins_send_telemetry_options is not None:
            _traceparent = digital_twins_send_telemetry_options.traceparent
            _tracestate = digital_twins_send_telemetry_options.tracestate
        _json = self._serialize.body(telemetry, "object")

        _request = build_send_telemetry_request(
            id=id,
            message_id=message_id,
            traceparent=_traceparent,
            tracestate=_tracestate,
            telemetry_source_time=telemetry_source_time,
            api_version=api_version,
            content_type=content_type,
            json=_json,
            headers=_headers,
            params=_params,
        )
        _request.url = self._client.format_url(_request.url)

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

        response = pipeline_response.http_response

        if response.status_code not in [204]:
            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, {})  # type: ignore

    @distributed_trace_async
    async def send_component_telemetry(
        self,
        id: str,
        component_path: str,
        message_id: str,
        telemetry: JSON,
        telemetry_source_time: Optional[str] = None,
        digital_twins_send_component_telemetry_options: Optional[
            _models.DigitalTwinsSendComponentTelemetryOptions
        ] = None,
        **kwargs: Any
    ) -> None:
        """Sends telemetry on behalf of a component in a digital twin.
        Status codes:


        * 204 No Content
        * 400 Bad Request

          * InvalidArgument - The digital twin id, message id, or component path is invalid.
          * ValidationFailed - The telemetry content is invalid.

        * 404 Not Found

          * DigitalTwinNotFound - The digital twin was not found.
          * ComponentNotFound - The component path was not found.

        :param id: The id of the digital twin. The id is unique within the service and case sensitive.
         Required.
        :type id: str
        :param component_path: The name of the DTDL component. Required.
        :type component_path: str
        :param message_id: A unique message identifier (in the scope of the digital twin id) that is
         commonly used for de-duplicating messages. Required.
        :type message_id: str
        :param telemetry: The telemetry measurements to send from the digital twin's component.
         Required.
        :type telemetry: JSON
        :param telemetry_source_time: An RFC 3339 timestamp that identifies the time the telemetry was
         measured. Default value is None.
        :type telemetry_source_time: str
        :param digital_twins_send_component_telemetry_options: Parameter group. Default value is None.
        :type digital_twins_send_component_telemetry_options:
         ~azure.digitaltwins.core.models.DigitalTwinsSendComponentTelemetryOptions
        :return: None or the result of cls(response)
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            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 = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version))
        content_type: str = kwargs.pop("content_type", _headers.pop("Content-Type", "application/json"))
        cls: ClsType[None] = kwargs.pop("cls", None)

        _traceparent = None
        _tracestate = None
        if digital_twins_send_component_telemetry_options is not None:
            _traceparent = digital_twins_send_component_telemetry_options.traceparent
            _tracestate = digital_twins_send_component_telemetry_options.tracestate
        _json = self._serialize.body(telemetry, "object")

        _request = build_send_component_telemetry_request(
            id=id,
            component_path=component_path,
            message_id=message_id,
            traceparent=_traceparent,
            tracestate=_tracestate,
            telemetry_source_time=telemetry_source_time,
            api_version=api_version,
            content_type=content_type,
            json=_json,
            headers=_headers,
            params=_params,
        )
        _request.url = self._client.format_url(_request.url)

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

        response = pipeline_response.http_response

        if response.status_code not in [204]:
            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, {})  # type: ignore

    @distributed_trace_async
    async def get_component(
        self,
        id: str,
        component_path: str,
        digital_twins_get_component_options: Optional[_models.DigitalTwinsGetComponentOptions] = None,
        **kwargs: Any
    ) -> Dict[str, Any]:
        """Retrieves a component from a digital twin.
        Status codes:


        * 200 OK
        * 400 Bad Request

          * InvalidArgument - The digital twin id or component path is invalid.

        * 404 Not Found

          * DigitalTwinNotFound - The digital twin was not found.
          * ComponentNotFound - The component path was not found.

        :param id: The id of the digital twin. The id is unique within the service and case sensitive.
         Required.
        :type id: str
        :param component_path: The name of the DTDL component. Required.
        :type component_path: str
        :param digital_twins_get_component_options: Parameter group. Default value is None.
        :type digital_twins_get_component_options:
         ~azure.digitaltwins.core.models.DigitalTwinsGetComponentOptions
        :return: dict mapping str to any or the result of cls(response)
        :rtype: dict[str, any]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

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

        api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version))
        cls: ClsType[Dict[str, Any]] = kwargs.pop("cls", None)

        _traceparent = None
        _tracestate = None
        if digital_twins_get_component_options is not None:
            _traceparent = digital_twins_get_component_options.traceparent
            _tracestate = digital_twins_get_component_options.tracestate

        _request = build_get_component_request(
            id=id,
            component_path=component_path,
            traceparent=_traceparent,
            tracestate=_tracestate,
            api_version=api_version,
            headers=_headers,
            params=_params,
        )
        _request.url = self._client.format_url(_request.url)

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

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            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)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

        deserialized = self._deserialize("{object}", pipeline_response.http_response)

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

        return deserialized  # type: ignore

    @overload
    async def update_component(
        self,
        id: str,
        component_path: str,
        patch_document: List[JSON],
        digital_twins_update_component_options: Optional[_models.DigitalTwinsUpdateComponentOptions] = None,
        *,
        content_type: str = "application/json-patch+json",
        **kwargs: Any
    ) -> None:
        """Updates a component on a digital twin.
        Status codes:


        * 204 No Content
        * 400 Bad Request

          * InvalidArgument - The digital twin id, component path, or payload is invalid.
          * JsonPatchInvalid - The JSON Patch provided is invalid.
          * ValidationFailed - Applying the patch results in an invalid digital twin.

        * 404 Not Found

          * DigitalTwinNotFound - The digital twin was not found.

        * 412 Precondition Failed

          * PreconditionFailed - The precondition check (If-Match or If-None-Match) failed.

        :param id: The id of the digital twin. The id is unique within the service and case sensitive.
         Required.
        :type id: str
        :param component_path: The name of the DTDL component. Required.
        :type component_path: str
        :param patch_document: An update specification described by JSON Patch. Updates to property
         values and $model elements may happen in the same request. Operations are limited to add,
         replace and remove. Required.
        :type patch_document: list[JSON]
        :param digital_twins_update_component_options: Parameter group. Default value is None.
        :type digital_twins_update_component_options:
         ~azure.digitaltwins.core.models.DigitalTwinsUpdateComponentOptions
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json-patch+json".
        :paramtype content_type: str
        :return: None or the result of cls(response)
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update_component(
        self,
        id: str,
        component_path: str,
        patch_document: IO[bytes],
        digital_twins_update_component_options: Optional[_models.DigitalTwinsUpdateComponentOptions] = None,
        *,
        content_type: str = "application/json-patch+json",
        **kwargs: Any
    ) -> None:
        """Updates a component on a digital twin.
        Status codes:


        * 204 No Content
        * 400 Bad Request

          * InvalidArgument - The digital twin id, component path, or payload is invalid.
          * JsonPatchInvalid - The JSON Patch provided is invalid.
          * ValidationFailed - Applying the patch results in an invalid digital twin.

        * 404 Not Found

          * DigitalTwinNotFound - The digital twin was not found.

        * 412 Precondition Failed

          * PreconditionFailed - The precondition check (If-Match or If-None-Match) failed.

        :param id: The id of the digital twin. The id is unique within the service and case sensitive.
         Required.
        :type id: str
        :param component_path: The name of the DTDL component. Required.
        :type component_path: str
        :param patch_document: An update specification described by JSON Patch. Updates to property
         values and $model elements may happen in the same request. Operations are limited to add,
         replace and remove. Required.
        :type patch_document: IO[bytes]
        :param digital_twins_update_component_options: Parameter group. Default value is None.
        :type digital_twins_update_component_options:
         ~azure.digitaltwins.core.models.DigitalTwinsUpdateComponentOptions
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json-patch+json".
        :paramtype content_type: str
        :return: None or the result of cls(response)
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def update_component(
        self,
        id: str,
        component_path: str,
        patch_document: Union[List[JSON], IO[bytes]],
        digital_twins_update_component_options: Optional[_models.DigitalTwinsUpdateComponentOptions] = None,
        **kwargs: Any
    ) -> None:
        """Updates a component on a digital twin.
        Status codes:


        * 204 No Content
        * 400 Bad Request

          * InvalidArgument - The digital twin id, component path, or payload is invalid.
          * JsonPatchInvalid - The JSON Patch provided is invalid.
          * ValidationFailed - Applying the patch results in an invalid digital twin.

        * 404 Not Found

          * DigitalTwinNotFound - The digital twin was not found.

        * 412 Precondition Failed

          * PreconditionFailed - The precondition check (If-Match or If-None-Match) failed.

        :param id: The id of the digital twin. The id is unique within the service and case sensitive.
         Required.
        :type id: str
        :param component_path: The name of the DTDL component. Required.
        :type component_path: str
        :param patch_document: An update specification described by JSON Patch. Updates to property
         values and $model elements may happen in the same request. Operations are limited to add,
         replace and remove. Is either a [JSON] type or a IO[bytes] type. Required.
        :type patch_document: list[JSON] or IO[bytes]
        :param digital_twins_update_component_options: Parameter group. Default value is None.
        :type digital_twins_update_component_options:
         ~azure.digitaltwins.core.models.DigitalTwinsUpdateComponentOptions
        :return: None or the result of cls(response)
        :rtype: None
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map: MutableMapping = {
            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 = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version: str = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version))
        content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
        cls: ClsType[None] = kwargs.pop("cls", None)

        _traceparent = None
        _tracestate = None
        _if_match = None
        if digital_twins_update_component_options is not None:
            _if_match = digital_twins_update_component_options.if_match
            _traceparent = digital_twins_update_component_options.traceparent
            _tracestate = digital_twins_update_component_options.tracestate
        content_type = content_type or "application/json-patch+json"
        _json = None
        _content = None
        if isinstance(patch_document, (IOBase, bytes)):
            _content = patch_document
        else:
            _json = self._serialize.body(patch_document, "[object]")

        _request = build_update_component_request(
            id=id,
            component_path=component_path,
            traceparent=_traceparent,
            tracestate=_tracestate,
            if_match=_if_match,
            api_version=api_version,
            content_type=content_type,
            json=_json,
            content=_content,
            headers=_headers,
            params=_params,
        )
        _request.url = self._client.format_url(_request.url)

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

        response = pipeline_response.http_response

        if response.status_code not in [204]:
            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)

        response_headers = {}
        response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))

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