# pylint: disable=line-too-long,useless-suppression,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) Python 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
import json
from typing import Any, AsyncIterator, Callable, IO, Optional, TypeVar, Union, cast, 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,
    StreamClosedError,
    StreamConsumedError,
    map_error,
)
from azure.core.pipeline import PipelineResponse
from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod
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 azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling

from ... import models as _models
from ..._utils.model_base import SdkJSONEncoder, _deserialize, _failsafe_deserialize
from ..._utils.serialization import Deserializer, Serializer
from ..._utils.utils import ClientMixinABC
from ...operations._operations import (
    build_entities_list_request,
    build_hierarchy_settings_create_or_update_request,
    build_hierarchy_settings_delete_request,
    build_hierarchy_settings_get_request,
    build_hierarchy_settings_list_request,
    build_hierarchy_settings_update_request,
    build_management_group_subscriptions_create_request,
    build_management_group_subscriptions_delete_request,
    build_management_group_subscriptions_get_subscription_request,
    build_management_group_subscriptions_get_subscriptions_under_management_group_request,
    build_management_groups_create_or_update_request,
    build_management_groups_delete_request,
    build_management_groups_get_descendants_request,
    build_management_groups_get_request,
    build_management_groups_list_request,
    build_management_groups_mgmt_check_name_availability_request,
    build_management_groups_mgmt_start_tenant_backfill_request,
    build_management_groups_mgmt_tenant_backfill_status_request,
    build_management_groups_update_request,
    build_operations_list_request,
)
from .._configuration import ManagementGroupsMgmtClientConfiguration

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


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

        Instead, you should access the following operations through
        :class:`~azure.mgmt.managementgroups.aio.ManagementGroupsMgmtClient`'s
        :attr:`operations` attribute.
    """

    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: ManagementGroupsMgmtClientConfiguration = (
            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
    def list(self, **kwargs: Any) -> AsyncItemPaged["_models.Operation"]:
        """List the operations for the provider.

        :return: An iterator like instance of Operation
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.managementgroups.models.Operation]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.Operation]] = 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:

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

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

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.Operation],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") 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 = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


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

        Instead, you should access the following operations through
        :class:`~azure.mgmt.managementgroups.aio.ManagementGroupsMgmtClient`'s
        :attr:`management_groups` attribute.
    """

    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: ManagementGroupsMgmtClientConfiguration = (
            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(
        self,
        group_id: str,
        *,
        expand: Optional[Union[str, _models.ManagementGroupExpandType]] = None,
        recurse: Optional[bool] = None,
        filter: Optional[str] = None,
        cache_control: str = "no-cache",
        **kwargs: Any
    ) -> _models.ManagementGroup:
        """Get the details of the management group.

        :param group_id: Management Group ID. Required.
        :type group_id: str
        :keyword expand: The $expand=children query string parameter allows clients to request
         inclusion of children in the response payload.  $expand=path includes the path from the root
         group to the current group.  $expand=ancestors includes the ancestor Ids of the current group.
         Known values are: "children", "path", and "ancestors". Default value is None.
        :paramtype expand: str or ~azure.mgmt.managementgroups.models.ManagementGroupExpandType
        :keyword recurse: The $recurse=true query string parameter allows clients to request inclusion
         of entire hierarchy in the response payload. Note that  $expand=children must be passed up if
         $recurse is set to true. Default value is None.
        :paramtype recurse: bool
        :keyword filter: A filter which allows the exclusion of subscriptions from results (i.e.
         '$filter=children.childType ne Subscription'). Default value is None.
        :paramtype filter: str
        :keyword cache_control: Indicates whether the request should utilize any caches. Populate the
         header with 'no-cache' value to bypass existing caches. Default value is "no-cache".
        :paramtype cache_control: str
        :return: ManagementGroup. The ManagementGroup is compatible with MutableMapping
        :rtype: ~azure.mgmt.managementgroups.models.ManagementGroup
        :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 = kwargs.pop("params", {}) or {}

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

        _request = build_management_groups_get_request(
            group_id=group_id,
            expand=expand,
            recurse=recurse,
            filter=filter,
            cache_control=cache_control,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("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]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.ManagementGroup, response.json())

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

        return deserialized  # type: ignore

    async def _create_or_update_initial(
        self,
        group_id: str,
        create_management_group_request: Union[_models.CreateManagementGroupRequest, JSON, IO[bytes]],
        *,
        cache_control: str = "no-cache",
        **kwargs: Any
    ) -> AsyncIterator[bytes]:
        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 = kwargs.pop("params", {}) or {}

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

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

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

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        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, 202]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 202:
            response_headers["Azure-AsyncOperation"] = self._deserialize(
                "str", response.headers.get("Azure-AsyncOperation")
            )
            response_headers["Location"] = self._deserialize("str", response.headers.get("Location"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

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

        return deserialized  # type: ignore

    @overload
    async def begin_create_or_update(
        self,
        group_id: str,
        create_management_group_request: _models.CreateManagementGroupRequest,
        *,
        cache_control: str = "no-cache",
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.ManagementGroup]:
        """Create or update a management group. If a management group is already created and a subsequent
        create request is issued with different properties, the management group properties will be
        updated.

        :param group_id: Management Group ID. Required.
        :type group_id: str
        :param create_management_group_request: Management group creation parameters. Required.
        :type create_management_group_request:
         ~azure.mgmt.managementgroups.models.CreateManagementGroupRequest
        :keyword cache_control: Indicates whether the request should utilize any caches. Populate the
         header with 'no-cache' value to bypass existing caches. Default value is "no-cache".
        :paramtype cache_control: str
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns ManagementGroup. The ManagementGroup is
         compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.managementgroups.models.ManagementGroup]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_create_or_update(
        self,
        group_id: str,
        create_management_group_request: JSON,
        *,
        cache_control: str = "no-cache",
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.ManagementGroup]:
        """Create or update a management group. If a management group is already created and a subsequent
        create request is issued with different properties, the management group properties will be
        updated.

        :param group_id: Management Group ID. Required.
        :type group_id: str
        :param create_management_group_request: Management group creation parameters. Required.
        :type create_management_group_request: JSON
        :keyword cache_control: Indicates whether the request should utilize any caches. Populate the
         header with 'no-cache' value to bypass existing caches. Default value is "no-cache".
        :paramtype cache_control: str
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns ManagementGroup. The ManagementGroup is
         compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.managementgroups.models.ManagementGroup]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def begin_create_or_update(
        self,
        group_id: str,
        create_management_group_request: IO[bytes],
        *,
        cache_control: str = "no-cache",
        content_type: str = "application/json",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.ManagementGroup]:
        """Create or update a management group. If a management group is already created and a subsequent
        create request is issued with different properties, the management group properties will be
        updated.

        :param group_id: Management Group ID. Required.
        :type group_id: str
        :param create_management_group_request: Management group creation parameters. Required.
        :type create_management_group_request: IO[bytes]
        :keyword cache_control: Indicates whether the request should utilize any caches. Populate the
         header with 'no-cache' value to bypass existing caches. Default value is "no-cache".
        :paramtype cache_control: str
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: An instance of AsyncLROPoller that returns ManagementGroup. The ManagementGroup is
         compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.managementgroups.models.ManagementGroup]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def begin_create_or_update(
        self,
        group_id: str,
        create_management_group_request: Union[_models.CreateManagementGroupRequest, JSON, IO[bytes]],
        *,
        cache_control: str = "no-cache",
        **kwargs: Any
    ) -> AsyncLROPoller[_models.ManagementGroup]:
        """Create or update a management group. If a management group is already created and a subsequent
        create request is issued with different properties, the management group properties will be
        updated.

        :param group_id: Management Group ID. Required.
        :type group_id: str
        :param create_management_group_request: Management group creation parameters. Is one of the
         following types: CreateManagementGroupRequest, JSON, IO[bytes] Required.
        :type create_management_group_request:
         ~azure.mgmt.managementgroups.models.CreateManagementGroupRequest or JSON or IO[bytes]
        :keyword cache_control: Indicates whether the request should utilize any caches. Populate the
         header with 'no-cache' value to bypass existing caches. Default value is "no-cache".
        :paramtype cache_control: str
        :return: An instance of AsyncLROPoller that returns ManagementGroup. The ManagementGroup is
         compatible with MutableMapping
        :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.managementgroups.models.ManagementGroup]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

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

        def get_long_running_output(pipeline_response):
            response = pipeline_response.http_response
            deserialized = _deserialize(_models.ManagementGroup, response.json())
            if cls:
                return cls(pipeline_response, deserialized, {})  # type: ignore
            return deserialized

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

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

    @overload
    async def update(
        self,
        group_id: str,
        patch_group_request: _models.PatchManagementGroupRequest,
        *,
        cache_control: str = "no-cache",
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.ManagementGroup:
        """Update a management group.

        :param group_id: Management Group ID. Required.
        :type group_id: str
        :param patch_group_request: Management group patch parameters. Required.
        :type patch_group_request: ~azure.mgmt.managementgroups.models.PatchManagementGroupRequest
        :keyword cache_control: Indicates whether the request should utilize any caches. Populate the
         header with 'no-cache' value to bypass existing caches. Default value is "no-cache".
        :paramtype cache_control: str
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: ManagementGroup. The ManagementGroup is compatible with MutableMapping
        :rtype: ~azure.mgmt.managementgroups.models.ManagementGroup
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        group_id: str,
        patch_group_request: JSON,
        *,
        cache_control: str = "no-cache",
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.ManagementGroup:
        """Update a management group.

        :param group_id: Management Group ID. Required.
        :type group_id: str
        :param patch_group_request: Management group patch parameters. Required.
        :type patch_group_request: JSON
        :keyword cache_control: Indicates whether the request should utilize any caches. Populate the
         header with 'no-cache' value to bypass existing caches. Default value is "no-cache".
        :paramtype cache_control: str
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: ManagementGroup. The ManagementGroup is compatible with MutableMapping
        :rtype: ~azure.mgmt.managementgroups.models.ManagementGroup
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        group_id: str,
        patch_group_request: IO[bytes],
        *,
        cache_control: str = "no-cache",
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.ManagementGroup:
        """Update a management group.

        :param group_id: Management Group ID. Required.
        :type group_id: str
        :param patch_group_request: Management group patch parameters. Required.
        :type patch_group_request: IO[bytes]
        :keyword cache_control: Indicates whether the request should utilize any caches. Populate the
         header with 'no-cache' value to bypass existing caches. Default value is "no-cache".
        :paramtype cache_control: str
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: ManagementGroup. The ManagementGroup is compatible with MutableMapping
        :rtype: ~azure.mgmt.managementgroups.models.ManagementGroup
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def update(
        self,
        group_id: str,
        patch_group_request: Union[_models.PatchManagementGroupRequest, JSON, IO[bytes]],
        *,
        cache_control: str = "no-cache",
        **kwargs: Any
    ) -> _models.ManagementGroup:
        """Update a management group.

        :param group_id: Management Group ID. Required.
        :type group_id: str
        :param patch_group_request: Management group patch parameters. Is one of the following types:
         PatchManagementGroupRequest, JSON, IO[bytes] Required.
        :type patch_group_request: ~azure.mgmt.managementgroups.models.PatchManagementGroupRequest or
         JSON or IO[bytes]
        :keyword cache_control: Indicates whether the request should utilize any caches. Populate the
         header with 'no-cache' value to bypass existing caches. Default value is "no-cache".
        :paramtype cache_control: str
        :return: ManagementGroup. The ManagementGroup is compatible with MutableMapping
        :rtype: ~azure.mgmt.managementgroups.models.ManagementGroup
        :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 = kwargs.pop("params", {}) or {}

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

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

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

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("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]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.ManagementGroup, response.json())

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

        return deserialized  # type: ignore

    async def _delete_initial(
        self, group_id: str, *, cache_control: str = "no-cache", **kwargs: Any
    ) -> AsyncIterator[bytes]:
        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 = kwargs.pop("params", {}) or {}

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

        _request = build_management_groups_delete_request(
            group_id=group_id,
            cache_control=cache_control,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = True
        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 [202, 204]:
            try:
                await response.read()  # Load the body in memory and close the socket
            except (StreamConsumedError, StreamClosedError):
                pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        response_headers = {}
        if response.status_code == 202:
            response_headers["Azure-AsyncOperation"] = self._deserialize(
                "str", response.headers.get("Azure-AsyncOperation")
            )
            response_headers["Location"] = self._deserialize("str", response.headers.get("Location"))
            response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After"))

        deserialized = response.iter_bytes() if _decompress else response.iter_raw()

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

        return deserialized  # type: ignore

    @distributed_trace_async
    async def begin_delete(
        self, group_id: str, *, cache_control: str = "no-cache", **kwargs: Any
    ) -> AsyncLROPoller[None]:
        """Delete management group. If a management group contains child resources, the request will fail.

        :param group_id: Management Group ID. Required.
        :type group_id: str
        :keyword cache_control: Indicates whether the request should utilize any caches. Populate the
         header with 'no-cache' value to bypass existing caches. Default value is "no-cache".
        :paramtype cache_control: str
        :return: An instance of AsyncLROPoller that returns None
        :rtype: ~azure.core.polling.AsyncLROPoller[None]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[None] = kwargs.pop("cls", None)
        polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True)
        lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
        cont_token: Optional[str] = kwargs.pop("continuation_token", None)
        if cont_token is None:
            raw_result = await self._delete_initial(
                group_id=group_id,
                cache_control=cache_control,
                cls=lambda x, y, z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
            await raw_result.http_response.read()  # type: ignore
        kwargs.pop("error_map", None)

        def get_long_running_output(pipeline_response):  # pylint: disable=inconsistent-return-statements
            if cls:
                return cls(pipeline_response, None, {})  # type: ignore

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

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

    @distributed_trace
    def get_descendants(
        self, group_id: str, *, skiptoken: Optional[str] = None, top: Optional[int] = None, **kwargs: Any
    ) -> AsyncItemPaged["_models.DescendantInfo"]:
        """List all entities that descend from a management group.

        :param group_id: Management Group ID. Required.
        :type group_id: str
        :keyword skiptoken: Page continuation token is only used if a previous operation returned a
         partial result.
         If a previous response contains a nextLink element, the value of the nextLink element will
         include a token parameter that specifies a starting point to use for subsequent calls. Default
         value is None.
        :paramtype skiptoken: str
        :keyword top: Number of elements to return when retrieving results. Passing this in will
         override $skipToken. Default value is None.
        :paramtype top: int
        :return: An iterator like instance of DescendantInfo
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.managementgroups.models.DescendantInfo]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.DescendantInfo]] = 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:

                _request = build_management_groups_get_descendants_request(
                    group_id=group_id,
                    skiptoken=skiptoken,
                    top=top,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

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

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.DescendantInfo],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") 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 = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)

    @distributed_trace
    def list(
        self, *, cache_control: str = "no-cache", skiptoken: Optional[str] = None, **kwargs: Any
    ) -> AsyncItemPaged["_models.ManagementGroupInfo"]:
        """List management groups for the authenticated user.

        :keyword cache_control: Indicates whether the request should utilize any caches. Populate the
         header with 'no-cache' value to bypass existing caches. Default value is "no-cache".
        :paramtype cache_control: str
        :keyword skiptoken: Page continuation token is only used if a previous operation returned a
         partial result.
         If a previous response contains a nextLink element, the value of the nextLink element will
         include a token parameter that specifies a starting point to use for subsequent calls. Default
         value is None.
        :paramtype skiptoken: str
        :return: An iterator like instance of ManagementGroupInfo
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.managementgroups.models.ManagementGroupInfo]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.ManagementGroupInfo]] = 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:

                _request = build_management_groups_list_request(
                    cache_control=cache_control,
                    skiptoken=skiptoken,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

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

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.ManagementGroupInfo],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("@nextLink") 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 = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


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

        Instead, you should access the following operations through
        :class:`~azure.mgmt.managementgroups.aio.ManagementGroupsMgmtClient`'s
        :attr:`hierarchy_settings` attribute.
    """

    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: ManagementGroupsMgmtClientConfiguration = (
            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 list(self, group_id: str, **kwargs: Any) -> _models.HierarchySettingsList:
        """Gets all the hierarchy settings defined at the Management Group level. Settings can only be set
        on the root Management Group of the hierarchy.

        :param group_id: Management Group ID. Required.
        :type group_id: str
        :return: HierarchySettingsList. The HierarchySettingsList is compatible with MutableMapping
        :rtype: ~azure.mgmt.managementgroups.models.HierarchySettingsList
        :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 = kwargs.pop("params", {}) or {}

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

        _request = build_hierarchy_settings_list_request(
            group_id=group_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("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]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.HierarchySettingsList, response.json())

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

        return deserialized  # type: ignore

    @distributed_trace_async
    async def get(self, group_id: str, **kwargs: Any) -> _models.HierarchySettings:
        """Gets the hierarchy settings defined at the Management Group level. Settings can only be set on
        the root Management Group of the hierarchy.

        :param group_id: Management Group ID. Required.
        :type group_id: str
        :return: HierarchySettings. The HierarchySettings is compatible with MutableMapping
        :rtype: ~azure.mgmt.managementgroups.models.HierarchySettings
        :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 = kwargs.pop("params", {}) or {}

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

        _request = build_hierarchy_settings_get_request(
            group_id=group_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("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]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.HierarchySettings, response.json())

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

        return deserialized  # type: ignore

    @overload
    async def create_or_update(
        self,
        group_id: str,
        create_tenant_settings_request: _models.CreateOrUpdateSettingsRequest,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.HierarchySettings:
        """Creates or updates the hierarchy settings defined at the Management Group level.

        :param group_id: Management Group ID. Required.
        :type group_id: str
        :param create_tenant_settings_request: Tenant level settings request parameter. Required.
        :type create_tenant_settings_request:
         ~azure.mgmt.managementgroups.models.CreateOrUpdateSettingsRequest
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: HierarchySettings. The HierarchySettings is compatible with MutableMapping
        :rtype: ~azure.mgmt.managementgroups.models.HierarchySettings
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        group_id: str,
        create_tenant_settings_request: JSON,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.HierarchySettings:
        """Creates or updates the hierarchy settings defined at the Management Group level.

        :param group_id: Management Group ID. Required.
        :type group_id: str
        :param create_tenant_settings_request: Tenant level settings request parameter. Required.
        :type create_tenant_settings_request: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: HierarchySettings. The HierarchySettings is compatible with MutableMapping
        :rtype: ~azure.mgmt.managementgroups.models.HierarchySettings
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def create_or_update(
        self,
        group_id: str,
        create_tenant_settings_request: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.HierarchySettings:
        """Creates or updates the hierarchy settings defined at the Management Group level.

        :param group_id: Management Group ID. Required.
        :type group_id: str
        :param create_tenant_settings_request: Tenant level settings request parameter. Required.
        :type create_tenant_settings_request: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: HierarchySettings. The HierarchySettings is compatible with MutableMapping
        :rtype: ~azure.mgmt.managementgroups.models.HierarchySettings
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def create_or_update(
        self,
        group_id: str,
        create_tenant_settings_request: Union[_models.CreateOrUpdateSettingsRequest, JSON, IO[bytes]],
        **kwargs: Any
    ) -> _models.HierarchySettings:
        """Creates or updates the hierarchy settings defined at the Management Group level.

        :param group_id: Management Group ID. Required.
        :type group_id: str
        :param create_tenant_settings_request: Tenant level settings request parameter. Is one of the
         following types: CreateOrUpdateSettingsRequest, JSON, IO[bytes] Required.
        :type create_tenant_settings_request:
         ~azure.mgmt.managementgroups.models.CreateOrUpdateSettingsRequest or JSON or IO[bytes]
        :return: HierarchySettings. The HierarchySettings is compatible with MutableMapping
        :rtype: ~azure.mgmt.managementgroups.models.HierarchySettings
        :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 = kwargs.pop("params", {}) or {}

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

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

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

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("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]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.HierarchySettings, response.json())

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

        return deserialized  # type: ignore

    @overload
    async def update(
        self,
        group_id: str,
        create_tenant_settings_request: _models.CreateOrUpdateSettingsRequest,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.HierarchySettings:
        """Updates the hierarchy settings defined at the Management Group level.

        :param group_id: Management Group ID. Required.
        :type group_id: str
        :param create_tenant_settings_request: Tenant level settings request parameter. Required.
        :type create_tenant_settings_request:
         ~azure.mgmt.managementgroups.models.CreateOrUpdateSettingsRequest
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: HierarchySettings. The HierarchySettings is compatible with MutableMapping
        :rtype: ~azure.mgmt.managementgroups.models.HierarchySettings
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        group_id: str,
        create_tenant_settings_request: JSON,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.HierarchySettings:
        """Updates the hierarchy settings defined at the Management Group level.

        :param group_id: Management Group ID. Required.
        :type group_id: str
        :param create_tenant_settings_request: Tenant level settings request parameter. Required.
        :type create_tenant_settings_request: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: HierarchySettings. The HierarchySettings is compatible with MutableMapping
        :rtype: ~azure.mgmt.managementgroups.models.HierarchySettings
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def update(
        self,
        group_id: str,
        create_tenant_settings_request: IO[bytes],
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.HierarchySettings:
        """Updates the hierarchy settings defined at the Management Group level.

        :param group_id: Management Group ID. Required.
        :type group_id: str
        :param create_tenant_settings_request: Tenant level settings request parameter. Required.
        :type create_tenant_settings_request: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: HierarchySettings. The HierarchySettings is compatible with MutableMapping
        :rtype: ~azure.mgmt.managementgroups.models.HierarchySettings
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def update(
        self,
        group_id: str,
        create_tenant_settings_request: Union[_models.CreateOrUpdateSettingsRequest, JSON, IO[bytes]],
        **kwargs: Any
    ) -> _models.HierarchySettings:
        """Updates the hierarchy settings defined at the Management Group level.

        :param group_id: Management Group ID. Required.
        :type group_id: str
        :param create_tenant_settings_request: Tenant level settings request parameter. Is one of the
         following types: CreateOrUpdateSettingsRequest, JSON, IO[bytes] Required.
        :type create_tenant_settings_request:
         ~azure.mgmt.managementgroups.models.CreateOrUpdateSettingsRequest or JSON or IO[bytes]
        :return: HierarchySettings. The HierarchySettings is compatible with MutableMapping
        :rtype: ~azure.mgmt.managementgroups.models.HierarchySettings
        :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 = kwargs.pop("params", {}) or {}

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

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

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

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("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]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.HierarchySettings, response.json())

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

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete(self, group_id: str, **kwargs: Any) -> None:
        """Deletes the hierarchy settings defined at the Management Group level.

        :param group_id: Management Group ID. Required.
        :type group_id: str
        :return: None
        :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 = kwargs.pop("params", {}) or {}

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

        _request = build_hierarchy_settings_delete_request(
            group_id=group_id,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _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 = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

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


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

        Instead, you should access the following operations through
        :class:`~azure.mgmt.managementgroups.aio.ManagementGroupsMgmtClient`'s
        :attr:`management_group_subscriptions` attribute.
    """

    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: ManagementGroupsMgmtClientConfiguration = (
            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_subscription(
        self, group_id: str, subscription_id: str, *, cache_control: str = "no-cache", **kwargs: Any
    ) -> _models.SubscriptionUnderManagementGroup:
        """Retrieves details about given subscription which is associated with the management group.

        :param group_id: Management Group ID. Required.
        :type group_id: str
        :param subscription_id: Subscription ID. Required.
        :type subscription_id: str
        :keyword cache_control: Indicates whether the request should utilize any caches. Populate the
         header with 'no-cache' value to bypass existing caches. Default value is "no-cache".
        :paramtype cache_control: str
        :return: SubscriptionUnderManagementGroup. The SubscriptionUnderManagementGroup is compatible
         with MutableMapping
        :rtype: ~azure.mgmt.managementgroups.models.SubscriptionUnderManagementGroup
        :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 = kwargs.pop("params", {}) or {}

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

        _request = build_management_group_subscriptions_get_subscription_request(
            group_id=group_id,
            subscription_id=subscription_id,
            cache_control=cache_control,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("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]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.SubscriptionUnderManagementGroup, response.json())

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

        return deserialized  # type: ignore

    @distributed_trace_async
    async def create(
        self, group_id: str, subscription_id: str, *, cache_control: str = "no-cache", **kwargs: Any
    ) -> _models.SubscriptionUnderManagementGroup:
        """Associates existing subscription with the management group.

        :param group_id: Management Group ID. Required.
        :type group_id: str
        :param subscription_id: Subscription ID. Required.
        :type subscription_id: str
        :keyword cache_control: Indicates whether the request should utilize any caches. Populate the
         header with 'no-cache' value to bypass existing caches. Default value is "no-cache".
        :paramtype cache_control: str
        :return: SubscriptionUnderManagementGroup. The SubscriptionUnderManagementGroup is compatible
         with MutableMapping
        :rtype: ~azure.mgmt.managementgroups.models.SubscriptionUnderManagementGroup
        :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 = kwargs.pop("params", {}) or {}

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

        _request = build_management_group_subscriptions_create_request(
            group_id=group_id,
            subscription_id=subscription_id,
            cache_control=cache_control,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _decompress = kwargs.pop("decompress", True)
        _stream = kwargs.pop("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]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.SubscriptionUnderManagementGroup, response.json())

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

        return deserialized  # type: ignore

    @distributed_trace_async
    async def delete(
        self, group_id: str, subscription_id: str, *, cache_control: str = "no-cache", **kwargs: Any
    ) -> None:
        """De-associates subscription from the management group.

        :param group_id: Management Group ID. Required.
        :type group_id: str
        :param subscription_id: Subscription ID. Required.
        :type subscription_id: str
        :keyword cache_control: Indicates whether the request should utilize any caches. Populate the
         header with 'no-cache' value to bypass existing caches. Default value is "no-cache".
        :paramtype cache_control: str
        :return: None
        :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 = kwargs.pop("params", {}) or {}

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

        _request = build_management_group_subscriptions_delete_request(
            group_id=group_id,
            subscription_id=subscription_id,
            cache_control=cache_control,
            api_version=self._config.api_version,
            headers=_headers,
            params=_params,
        )
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.base_url", self._config.base_url, "str", skip_quote=True),
        }
        _request.url = self._client.format_url(_request.url, **path_format_arguments)

        _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, 204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

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

    @distributed_trace
    def get_subscriptions_under_management_group(
        self, group_id: str, *, skiptoken: Optional[str] = None, **kwargs: Any
    ) -> AsyncItemPaged["_models.SubscriptionUnderManagementGroup"]:
        """Retrieves details about all subscriptions which are associated with the management group.

        :param group_id: Management Group ID. Required.
        :type group_id: str
        :keyword skiptoken: Page continuation token is only used if a previous operation returned a
         partial result.
         If a previous response contains a nextLink element, the value of the nextLink element will
         include a token parameter that specifies a starting point to use for subsequent calls. Default
         value is None.
        :paramtype skiptoken: str
        :return: An iterator like instance of SubscriptionUnderManagementGroup
        :rtype:
         ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.managementgroups.models.SubscriptionUnderManagementGroup]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.SubscriptionUnderManagementGroup]] = 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:

                _request = build_management_group_subscriptions_get_subscriptions_under_management_group_request(
                    group_id=group_id,
                    skiptoken=skiptoken,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

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

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.SubscriptionUnderManagementGroup],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") 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 = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


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

        Instead, you should access the following operations through
        :class:`~azure.mgmt.managementgroups.aio.ManagementGroupsMgmtClient`'s
        :attr:`entities` attribute.
    """

    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: ManagementGroupsMgmtClientConfiguration = (
            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
    def list(
        self,
        *,
        skiptoken: Optional[str] = None,
        skip: Optional[int] = None,
        top: Optional[int] = None,
        select: Optional[str] = None,
        search: Optional[Union[str, _models.EntitySearchType]] = None,
        filter: Optional[str] = None,
        view: Optional[Union[str, _models.EntityViewParameterType]] = None,
        group_name: Optional[str] = None,
        cache_control: str = "no-cache",
        **kwargs: Any
    ) -> AsyncItemPaged["_models.EntityInfo"]:
        """List all entities (Management Groups, Subscriptions, etc.) for the authenticated user.

        :keyword skiptoken: Page continuation token is only used if a previous operation returned a
         partial result.
         If a previous response contains a nextLink element, the value of the nextLink element will
         include a token parameter that specifies a starting point to use for subsequent calls. Default
         value is None.
        :paramtype skiptoken: str
        :keyword skip: Number of entities to skip over when retrieving results. Passing this in will
         override $skipToken. Default value is None.
        :paramtype skip: int
        :keyword top: Number of elements to return when retrieving results. Passing this in will
         override $skipToken. Default value is None.
        :paramtype top: int
        :keyword select: This parameter specifies the fields to include in the response. Can include
         any combination of Name,DisplayName,Type,ParentDisplayNameChain,ParentChain, e.g.
         '$select=Name,DisplayName,Type,ParentDisplayNameChain,ParentNameChain'. When specified the
         $select parameter can override select in $skipToken. Default value is None.
        :paramtype select: str
        :keyword search: The $search parameter is used in conjunction with the $filter parameter to
         return three different outputs depending on the parameter passed in.
         With $search=AllowedParents the API will return the entity info of all groups that the
         requested entity will be able to reparent to as determined by the user's permissions.
         With $search=AllowedChildren the API will return the entity info of all entities that can be
         added as children of the requested entity.
         With $search=ParentAndFirstLevelChildren the API will return the parent and  first level of
         children that the user has either direct access to or indirect access via one of their
         descendants.
         With $search=ParentOnly the API will return only the group if the user has access to at least
         one of the descendants of the group.
         With $search=ChildrenOnly the API will return only the first level of children of the group
         entity info specified in $filter.  The user must have direct access to the children entities or
         one of it's descendants for it to show up in the results. Known values are: "AllowedParents",
         "AllowedChildren", "ParentAndFirstLevelChildren", "ParentOnly", and "ChildrenOnly". Default
         value is None.
        :paramtype search: str or ~azure.mgmt.managementgroups.models.EntitySearchType
        :keyword filter: The filter parameter allows you to filter on the the name or display name
         fields. You can check for equality on the name field (e.g. name eq '{entityName}')  and you can
         check for substrings on either the name or display name fields(e.g. contains(name,
         '{substringToSearch}'), contains(displayName, '{substringToSearch')). Note that the
         '{entityName}' and '{substringToSearch}' fields are checked case insensitively. Default value
         is None.
        :paramtype filter: str
        :keyword view: The view parameter allows clients to filter the type of data that is returned by
         the getEntities call. Known values are: "FullHierarchy", "GroupsOnly", "SubscriptionsOnly", and
         "Audit". Default value is None.
        :paramtype view: str or ~azure.mgmt.managementgroups.models.EntityViewParameterType
        :keyword group_name: A filter which allows the get entities call to focus on a particular group
         (i.e. "$filter=name eq 'groupName'"). Default value is None.
        :paramtype group_name: str
        :keyword cache_control: Indicates whether the request should utilize any caches. Populate the
         header with 'no-cache' value to bypass existing caches. Default value is "no-cache".
        :paramtype cache_control: str
        :return: An iterator like instance of EntityInfo
        :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.managementgroups.models.EntityInfo]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls: ClsType[List[_models.EntityInfo]] = 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:

                _request = build_entities_list_request(
                    skiptoken=skiptoken,
                    skip=skip,
                    top=top,
                    select=select,
                    search=search,
                    filter=filter,
                    view=view,
                    group_name=group_name,
                    cache_control=cache_control,
                    api_version=self._config.api_version,
                    headers=_headers,
                    params=_params,
                )
                path_format_arguments = {
                    "endpoint": self._serialize.url(
                        "self._config.base_url", self._config.base_url, "str", skip_quote=True
                    ),
                }
                _request.url = self._client.format_url(_request.url, **path_format_arguments)

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

            return _request

        async def extract_data(pipeline_response):
            deserialized = pipeline_response.http_response.json()
            list_of_elem = _deserialize(
                List[_models.EntityInfo],
                deserialized.get("value", []),
            )
            if cls:
                list_of_elem = cls(list_of_elem)  # type: ignore
            return deserialized.get("nextLink") 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 = _failsafe_deserialize(
                    _models.ErrorResponse,
                    response,
                )
                raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

            return pipeline_response

        return AsyncItemPaged(get_next, extract_data)


class _ManagementGroupsMgmtClientOperationsMixin(
    ClientMixinABC[AsyncPipelineClient[HttpRequest, AsyncHttpResponse], ManagementGroupsMgmtClientConfiguration]
):

    @overload
    async def check_name_availability(
        self,
        check_name_availability_request: _models.CheckNameAvailabilityRequest,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> _models.CheckNameAvailabilityResult:
        """Checks if the specified management group name is valid and unique.

        :param check_name_availability_request: The request body. Required.
        :type check_name_availability_request:
         ~azure.mgmt.managementgroups.models.CheckNameAvailabilityRequest
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: CheckNameAvailabilityResult. The CheckNameAvailabilityResult is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.managementgroups.models.CheckNameAvailabilityResult
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def check_name_availability(
        self, check_name_availability_request: JSON, *, content_type: str = "application/json", **kwargs: Any
    ) -> _models.CheckNameAvailabilityResult:
        """Checks if the specified management group name is valid and unique.

        :param check_name_availability_request: The request body. Required.
        :type check_name_availability_request: JSON
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: CheckNameAvailabilityResult. The CheckNameAvailabilityResult is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.managementgroups.models.CheckNameAvailabilityResult
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    async def check_name_availability(
        self, check_name_availability_request: IO[bytes], *, content_type: str = "application/json", **kwargs: Any
    ) -> _models.CheckNameAvailabilityResult:
        """Checks if the specified management group name is valid and unique.

        :param check_name_availability_request: The request body. Required.
        :type check_name_availability_request: IO[bytes]
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :return: CheckNameAvailabilityResult. The CheckNameAvailabilityResult is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.managementgroups.models.CheckNameAvailabilityResult
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace_async
    async def check_name_availability(
        self,
        check_name_availability_request: Union[_models.CheckNameAvailabilityRequest, JSON, IO[bytes]],
        **kwargs: Any
    ) -> _models.CheckNameAvailabilityResult:
        """Checks if the specified management group name is valid and unique.

        :param check_name_availability_request: The request body. Is one of the following types:
         CheckNameAvailabilityRequest, JSON, IO[bytes] Required.
        :type check_name_availability_request:
         ~azure.mgmt.managementgroups.models.CheckNameAvailabilityRequest or JSON or IO[bytes]
        :return: CheckNameAvailabilityResult. The CheckNameAvailabilityResult is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.managementgroups.models.CheckNameAvailabilityResult
        :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 = kwargs.pop("params", {}) or {}

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

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

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

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

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.CheckNameAvailabilityResult, response.json())

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

        return deserialized  # type: ignore

    @distributed_trace_async
    async def start_tenant_backfill(self, **kwargs: Any) -> _models.TenantBackfillStatusResult:
        """Starts backfilling subscriptions for the Tenant.

        :return: TenantBackfillStatusResult. The TenantBackfillStatusResult is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.managementgroups.models.TenantBackfillStatusResult
        :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 = kwargs.pop("params", {}) or {}

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

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

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

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.TenantBackfillStatusResult, response.json())

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

        return deserialized  # type: ignore

    @distributed_trace_async
    async def tenant_backfill_status(self, **kwargs: Any) -> _models.TenantBackfillStatusResult:
        """Gets tenant backfill status.

        :return: TenantBackfillStatusResult. The TenantBackfillStatusResult is compatible with
         MutableMapping
        :rtype: ~azure.mgmt.managementgroups.models.TenantBackfillStatusResult
        :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 = kwargs.pop("params", {}) or {}

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

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

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

        response = pipeline_response.http_response

        if response.status_code not in [200]:
            if _stream:
                try:
                    await response.read()  # Load the body in memory and close the socket
                except (StreamConsumedError, StreamClosedError):
                    pass
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = _failsafe_deserialize(
                _models.ErrorResponse,
                response,
            )
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        if _stream:
            deserialized = response.iter_bytes() if _decompress else response.iter_raw()
        else:
            deserialized = _deserialize(_models.TenantBackfillStatusResult, response.json())

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

        return deserialized  # type: ignore
