# pylint: disable=too-many-lines
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from typing import Any, AsyncIterable, Callable, Dict, List, Optional, TypeVar

from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.tracing.decorator_async import distributed_trace_async

from ... import models as _models
from ..._vendor import _convert_request
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
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:
        args = list(args)
        self._client = args.pop(0) if args else kwargs.pop("client")
        self._config = args.pop(0) if args else kwargs.pop("config")
        self._serialize = args.pop(0) if args else kwargs.pop("serializer")
        self._deserialize = args.pop(0) if 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
    ) -> 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.
        :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
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: any, or the result of cls(response)
        :rtype: any
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        cls = kwargs.pop('cls', None)  # type: ClsType[Any]
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}))

        api_version = kwargs.pop('api_version', "2022-05-31")  # type: str

        _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,
            api_version=api_version,
            traceparent=_traceparent,
            tracestate=_tracestate,
            template_url=self.get_by_id.metadata['url'],
        )
        request = _convert_request(request)
        request.url = self._client.format_url(request.url)

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

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
            raise HttpResponseError(response=response, model=error)

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

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

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

        return deserialized

    get_by_id.metadata = {'url': "/digitaltwins/{id}"}  # type: ignore


    @distributed_trace_async
    async def add(
        self,
        id: str,
        twin: Any,
        digital_twins_add_options: Optional["_models.DigitalTwinsAddOptions"] = None,
        **kwargs: Any
    ) -> Optional[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.
        :type id: str
        :param twin: The digital twin instance being added. If provided, the $dtId property is ignored.
        :type twin: any
        :param digital_twins_add_options: Parameter group. Default value is None.
        :type digital_twins_add_options: ~azure.digitaltwins.core.models.DigitalTwinsAddOptions
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: any, or the result of cls(response)
        :rtype: any or None
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        cls = kwargs.pop('cls', None)  # type: ClsType[Optional[Any]]
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}))

        api_version = kwargs.pop('api_version', "2022-05-31")  # type: str
        content_type = kwargs.pop('content_type', "application/json")  # type: Optional[str]

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

        request = build_add_request(
            id=id,
            api_version=api_version,
            content_type=content_type,
            json=_json,
            traceparent=_traceparent,
            tracestate=_tracestate,
            if_none_match=_if_none_match,
            template_url=self.add.metadata['url'],
        )
        request = _convert_request(request)
        request.url = self._client.format_url(request.url)

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

        if response.status_code not in [200, 202]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
            raise HttpResponseError(response=response, model=error)

        deserialized = None
        response_headers = {}
        if response.status_code == 200:
            response_headers['ETag']=self._deserialize('str', response.headers.get('ETag'))
            
            deserialized = self._deserialize('object', pipeline_response)

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

        return deserialized

    add.metadata = {'url': "/digitaltwins/{id}"}  # type: ignore


    @distributed_trace_async
    async def delete(  # pylint: disable=inconsistent-return-statements
        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.
        :type id: str
        :param digital_twins_delete_options: Parameter group. Default value is None.
        :type digital_twins_delete_options: ~azure.digitaltwins.core.models.DigitalTwinsDeleteOptions
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: None, or the result of cls(response)
        :rtype: None
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        cls = kwargs.pop('cls', None)  # type: ClsType[None]
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}))

        api_version = kwargs.pop('api_version', "2022-05-31")  # type: str

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

        request = build_delete_request(
            id=id,
            api_version=api_version,
            traceparent=_traceparent,
            tracestate=_tracestate,
            if_match=_if_match,
            template_url=self.delete.metadata['url'],
        )
        request = _convert_request(request)
        request.url = self._client.format_url(request.url)

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

        if response.status_code not in [204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
            raise HttpResponseError(response=response, model=error)

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

    delete.metadata = {'url': "/digitaltwins/{id}"}  # type: ignore


    @distributed_trace_async
    async def update(  # pylint: disable=inconsistent-return-statements
        self,
        id: str,
        patch_document: List[Any],
        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.
        :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.
        :type patch_document: list[any]
        :param digital_twins_update_options: Parameter group. Default value is None.
        :type digital_twins_update_options: ~azure.digitaltwins.core.models.DigitalTwinsUpdateOptions
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: None, or the result of cls(response)
        :rtype: None
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        cls = kwargs.pop('cls', None)  # type: ClsType[None]
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}))

        api_version = kwargs.pop('api_version', "2022-05-31")  # type: str
        content_type = kwargs.pop('content_type', "application/json-patch+json")  # type: Optional[str]

        _traceparent = None
        _tracestate = None
        _if_match = None
        if digital_twins_update_options is not None:
            _traceparent = digital_twins_update_options.traceparent
            _tracestate = digital_twins_update_options.tracestate
            _if_match = digital_twins_update_options.if_match
        _json = self._serialize.body(patch_document, '[object]')

        request = build_update_request(
            id=id,
            api_version=api_version,
            content_type=content_type,
            json=_json,
            traceparent=_traceparent,
            tracestate=_tracestate,
            if_match=_if_match,
            template_url=self.update.metadata['url'],
        )
        request = _convert_request(request)
        request.url = self._client.format_url(request.url)

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

        if response.status_code not in [202, 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 = {}
        if response.status_code == 204:
            response_headers['ETag']=self._deserialize('str', response.headers.get('ETag'))
            

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

    update.metadata = {'url': "/digitaltwins/{id}"}  # 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
    ) -> 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.
        :type id: str
        :param relationship_id: The id of the relationship. The id is unique within the digital twin
         and case sensitive.
        :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
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: any, or the result of cls(response)
        :rtype: any
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        cls = kwargs.pop('cls', None)  # type: ClsType[Any]
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}))

        api_version = kwargs.pop('api_version', "2022-05-31")  # type: str

        _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,
            api_version=api_version,
            traceparent=_traceparent,
            tracestate=_tracestate,
            template_url=self.get_relationship_by_id.metadata['url'],
        )
        request = _convert_request(request)
        request.url = self._client.format_url(request.url)

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

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
            raise HttpResponseError(response=response, model=error)

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

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

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

        return deserialized

    get_relationship_by_id.metadata = {'url': "/digitaltwins/{id}/relationships/{relationshipId}"}  # type: ignore


    @distributed_trace_async
    async def add_relationship(
        self,
        id: str,
        relationship_id: str,
        relationship: Any,
        digital_twins_add_relationship_options: Optional["_models.DigitalTwinsAddRelationshipOptions"] = None,
        **kwargs: Any
    ) -> 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.
        :type id: str
        :param relationship_id: The id of the relationship. The id is unique within the digital twin
         and case sensitive.
        :type relationship_id: str
        :param relationship: The data for the relationship.
        :type relationship: any
        :param digital_twins_add_relationship_options: Parameter group. Default value is None.
        :type digital_twins_add_relationship_options:
         ~azure.digitaltwins.core.models.DigitalTwinsAddRelationshipOptions
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: any, or the result of cls(response)
        :rtype: any
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        cls = kwargs.pop('cls', None)  # type: ClsType[Any]
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}))

        api_version = kwargs.pop('api_version', "2022-05-31")  # type: str
        content_type = kwargs.pop('content_type', "application/json")  # type: Optional[str]

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

        request = build_add_relationship_request(
            id=id,
            relationship_id=relationship_id,
            api_version=api_version,
            content_type=content_type,
            json=_json,
            traceparent=_traceparent,
            tracestate=_tracestate,
            if_none_match=_if_none_match,
            template_url=self.add_relationship.metadata['url'],
        )
        request = _convert_request(request)
        request.url = self._client.format_url(request.url)

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

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
            raise HttpResponseError(response=response, model=error)

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

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

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

        return deserialized

    add_relationship.metadata = {'url': "/digitaltwins/{id}/relationships/{relationshipId}"}  # type: ignore


    @distributed_trace_async
    async def delete_relationship(  # pylint: disable=inconsistent-return-statements
        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.
        :type id: str
        :param relationship_id: The id of the relationship. The id is unique within the digital twin
         and case sensitive.
        :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
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: None, or the result of cls(response)
        :rtype: None
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        cls = kwargs.pop('cls', None)  # type: ClsType[None]
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}))

        api_version = kwargs.pop('api_version', "2022-05-31")  # type: str

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

        request = build_delete_relationship_request(
            id=id,
            relationship_id=relationship_id,
            api_version=api_version,
            traceparent=_traceparent,
            tracestate=_tracestate,
            if_match=_if_match,
            template_url=self.delete_relationship.metadata['url'],
        )
        request = _convert_request(request)
        request.url = self._client.format_url(request.url)

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

        if response.status_code not in [204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
            raise HttpResponseError(response=response, model=error)

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

    delete_relationship.metadata = {'url': "/digitaltwins/{id}/relationships/{relationshipId}"}  # type: ignore


    @distributed_trace_async
    async def update_relationship(  # pylint: disable=inconsistent-return-statements
        self,
        id: str,
        relationship_id: str,
        patch_document: List[Any],
        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.
        :type id: str
        :param relationship_id: The id of the relationship. The id is unique within the digital twin
         and case sensitive.
        :type relationship_id: str
        :param patch_document: JSON Patch description of the update to the relationship properties.
        :type patch_document: list[any]
        :param digital_twins_update_relationship_options: Parameter group. Default value is None.
        :type digital_twins_update_relationship_options:
         ~azure.digitaltwins.core.models.DigitalTwinsUpdateRelationshipOptions
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: None, or the result of cls(response)
        :rtype: None
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        cls = kwargs.pop('cls', None)  # type: ClsType[None]
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}))

        api_version = kwargs.pop('api_version', "2022-05-31")  # type: str
        content_type = kwargs.pop('content_type', "application/json-patch+json")  # type: Optional[str]

        _traceparent = None
        _tracestate = None
        _if_match = None
        if digital_twins_update_relationship_options is not None:
            _traceparent = digital_twins_update_relationship_options.traceparent
            _tracestate = digital_twins_update_relationship_options.tracestate
            _if_match = digital_twins_update_relationship_options.if_match
        _json = self._serialize.body(patch_document, '[object]')

        request = build_update_relationship_request(
            id=id,
            relationship_id=relationship_id,
            api_version=api_version,
            content_type=content_type,
            json=_json,
            traceparent=_traceparent,
            tracestate=_tracestate,
            if_match=_if_match,
            template_url=self.update_relationship.metadata['url'],
        )
        request = _convert_request(request)
        request.url = self._client.format_url(request.url)

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

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

    update_relationship.metadata = {'url': "/digitaltwins/{id}/relationships/{relationshipId}"}  # 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
    ) -> AsyncIterable["_models.RelationshipCollection"]:
        """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.
        :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
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: An iterator like instance of either RelationshipCollection or the result of
         cls(response)
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.digitaltwins.core.models.RelationshipCollection]
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        api_version = kwargs.pop('api_version', "2022-05-31")  # type: str

        cls = kwargs.pop('cls', None)  # type: ClsType["_models.RelationshipCollection"]
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}))
        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,
                    api_version=api_version,
                    traceparent=_traceparent,
                    tracestate=_tracestate,
                    relationship_name=relationship_name,
                    template_url=self.list_relationships.metadata['url'],
                )
                request = _convert_request(request)
                request.url = self._client.format_url(request.url)

            else:
                _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,
                    api_version=api_version,
                    traceparent=_traceparent,
                    tracestate=_tracestate,
                    relationship_name=relationship_name,
                    template_url=next_link,
                )
                request = _convert_request(request)
                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)
            return deserialized.next_link or None, AsyncList(list_of_elem)

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

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

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
                raise HttpResponseError(response=response, model=error)

            return pipeline_response


        return AsyncItemPaged(
            get_next, extract_data
        )
    list_relationships.metadata = {'url': "/digitaltwins/{id}/relationships"}  # type: ignore

    @distributed_trace
    def list_incoming_relationships(
        self,
        id: str,
        digital_twins_list_incoming_relationships_options: Optional["_models.DigitalTwinsListIncomingRelationshipsOptions"] = None,
        **kwargs: Any
    ) -> AsyncIterable["_models.IncomingRelationshipCollection"]:
        """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.
        :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
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: An iterator like instance of either IncomingRelationshipCollection or the result of
         cls(response)
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.digitaltwins.core.models.IncomingRelationshipCollection]
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        api_version = kwargs.pop('api_version', "2022-05-31")  # type: str

        cls = kwargs.pop('cls', None)  # type: ClsType["_models.IncomingRelationshipCollection"]
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}))
        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,
                    api_version=api_version,
                    traceparent=_traceparent,
                    tracestate=_tracestate,
                    template_url=self.list_incoming_relationships.metadata['url'],
                )
                request = _convert_request(request)
                request.url = self._client.format_url(request.url)

            else:
                _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,
                    api_version=api_version,
                    traceparent=_traceparent,
                    tracestate=_tracestate,
                    template_url=next_link,
                )
                request = _convert_request(request)
                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)
            return deserialized.next_link or None, AsyncList(list_of_elem)

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

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

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
                raise HttpResponseError(response=response, model=error)

            return pipeline_response


        return AsyncItemPaged(
            get_next, extract_data
        )
    list_incoming_relationships.metadata = {'url': "/digitaltwins/{id}/incomingrelationships"}  # type: ignore

    @distributed_trace_async
    async def send_telemetry(  # pylint: disable=inconsistent-return-statements
        self,
        id: str,
        message_id: str,
        telemetry: Any,
        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.
        :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.
        :type message_id: str
        :param telemetry: The telemetry measurements to send from the digital twin.
        :type telemetry: any
        :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
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: None, or the result of cls(response)
        :rtype: None
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        cls = kwargs.pop('cls', None)  # type: ClsType[None]
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}))

        api_version = kwargs.pop('api_version', "2022-05-31")  # type: str
        content_type = kwargs.pop('content_type', "application/json")  # type: Optional[str]

        _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,
            api_version=api_version,
            content_type=content_type,
            message_id=message_id,
            json=_json,
            traceparent=_traceparent,
            tracestate=_tracestate,
            telemetry_source_time=telemetry_source_time,
            template_url=self.send_telemetry.metadata['url'],
        )
        request = _convert_request(request)
        request.url = self._client.format_url(request.url)

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

        if response.status_code not in [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, {})

    send_telemetry.metadata = {'url': "/digitaltwins/{id}/telemetry"}  # type: ignore


    @distributed_trace_async
    async def send_component_telemetry(  # pylint: disable=inconsistent-return-statements
        self,
        id: str,
        component_path: str,
        message_id: str,
        telemetry: Any,
        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.
        :type id: str
        :param component_path: The name of the DTDL component.
        :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.
        :type message_id: str
        :param telemetry: The telemetry measurements to send from the digital twin's component.
        :type telemetry: any
        :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
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: None, or the result of cls(response)
        :rtype: None
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        cls = kwargs.pop('cls', None)  # type: ClsType[None]
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}))

        api_version = kwargs.pop('api_version', "2022-05-31")  # type: str
        content_type = kwargs.pop('content_type', "application/json")  # type: Optional[str]

        _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,
            api_version=api_version,
            content_type=content_type,
            message_id=message_id,
            json=_json,
            traceparent=_traceparent,
            tracestate=_tracestate,
            telemetry_source_time=telemetry_source_time,
            template_url=self.send_component_telemetry.metadata['url'],
        )
        request = _convert_request(request)
        request.url = self._client.format_url(request.url)

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

        if response.status_code not in [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, {})

    send_component_telemetry.metadata = {'url': "/digitaltwins/{id}/components/{componentPath}/telemetry"}  # 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
    ) -> 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.
        :type id: str
        :param component_path: The name of the DTDL component.
        :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
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: any, or the result of cls(response)
        :rtype: any
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        cls = kwargs.pop('cls', None)  # type: ClsType[Any]
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}))

        api_version = kwargs.pop('api_version', "2022-05-31")  # type: str

        _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,
            api_version=api_version,
            traceparent=_traceparent,
            tracestate=_tracestate,
            template_url=self.get_component.metadata['url'],
        )
        request = _convert_request(request)
        request.url = self._client.format_url(request.url)

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

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
            raise HttpResponseError(response=response, model=error)

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

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

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

        return deserialized

    get_component.metadata = {'url': "/digitaltwins/{id}/components/{componentPath}"}  # type: ignore


    @distributed_trace_async
    async def update_component(  # pylint: disable=inconsistent-return-statements
        self,
        id: str,
        component_path: str,
        patch_document: List[Any],
        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.
        :type id: str
        :param component_path: The name of the DTDL component.
        :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.
        :type patch_document: list[any]
        :param digital_twins_update_component_options: Parameter group. Default value is None.
        :type digital_twins_update_component_options:
         ~azure.digitaltwins.core.models.DigitalTwinsUpdateComponentOptions
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: None, or the result of cls(response)
        :rtype: None
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        cls = kwargs.pop('cls', None)  # type: ClsType[None]
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}))

        api_version = kwargs.pop('api_version', "2022-05-31")  # type: str
        content_type = kwargs.pop('content_type', "application/json-patch+json")  # type: Optional[str]

        _traceparent = None
        _tracestate = None
        _if_match = None
        if digital_twins_update_component_options is not None:
            _traceparent = digital_twins_update_component_options.traceparent
            _tracestate = digital_twins_update_component_options.tracestate
            _if_match = digital_twins_update_component_options.if_match
        _json = self._serialize.body(patch_document, '[object]')

        request = build_update_component_request(
            id=id,
            component_path=component_path,
            api_version=api_version,
            content_type=content_type,
            json=_json,
            traceparent=_traceparent,
            tracestate=_tracestate,
            if_match=_if_match,
            template_url=self.update_component.metadata['url'],
        )
        request = _convert_request(request)
        request.url = self._client.format_url(request.url)

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

        if response.status_code not in [202, 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 = {}
        if response.status_code == 204:
            response_headers['ETag']=self._deserialize('str', response.headers.get('ETag'))
            

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

    update_component.metadata = {'url': "/digitaltwins/{id}/components/{componentPath}"}  # type: ignore

