# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------

import uuid
from msrest.pipeline import ClientRawResponse
from msrestazure.azure_exceptions import CloudError
from msrest.polling import LROPoller, NoPolling
from msrestazure.polling.arm_polling import ARMPolling

from .. import models

class VaultsOperations(object):
    """VaultsOperations operations.

    :param client: Client for service requests.
    :param config: Configuration of service client.
    :param serializer: An object model serializer.
    :param deserializer: An object model deserializer.
    :ivar filter: The filter to apply on the operation. Constant value: "resourceType eq 'Microsoft.KeyVault/vaults'".
    """

    models = models

    def __init__(self, client, config, serializer, deserializer):

        self._client = client
        self._serialize = serializer
        self._deserialize = deserializer
        self.filter = "resourceType eq 'Microsoft.KeyVault/vaults'"

        self.config = config

    def create_or_update(
            self, resource_group_name, vault_name, parameters, custom_headers=None, raw=False, **operation_config):
        """Create or update a key vault in the specified subscription.

        :param resource_group_name: The name of the Resource Group to which
         the server belongs.
        :type resource_group_name: str
        :param vault_name: Name of the vault
        :type vault_name: str
        :param parameters: Parameters to create or update the vault
        :type parameters:
         ~azure.mgmt.keyvault.v2016_10_01.models.VaultCreateOrUpdateParameters
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: Vault or ClientRawResponse if raw=true
        :rtype: ~azure.mgmt.keyvault.v2016_10_01.models.Vault or
         ~msrest.pipeline.ClientRawResponse
        :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
        """
        api_version = "2016-10-01"

        # Construct URL
        url = self.create_or_update.metadata['url']
        path_format_arguments = {
            'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
            'vaultName': self._serialize.url("vault_name", vault_name, 'str', pattern=r'^[a-zA-Z0-9-]{3,24}$'),
            'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}
        query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if self.config.generate_client_request_id:
            header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
        if custom_headers:
            header_parameters.update(custom_headers)
        if self.config.accept_language is not None:
            header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')

        # Construct body
        body_content = self._serialize.body(parameters, 'VaultCreateOrUpdateParameters')

        # Construct and send request
        request = self._client.put(url, query_parameters)
        response = self._client.send(
            request, header_parameters, body_content, stream=False, **operation_config)

        if response.status_code not in [200, 201]:
            exp = CloudError(response)
            exp.request_id = response.headers.get('x-ms-request-id')
            raise exp

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('Vault', response)
        if response.status_code == 201:
            deserialized = self._deserialize('Vault', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized
    create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/vaults/{vaultName}'}

    def update(
            self, resource_group_name, vault_name, tags=None, properties=None, custom_headers=None, raw=False, **operation_config):
        """Update a key vault in the specified subscription.

        :param resource_group_name: The name of the Resource Group to which
         the server belongs.
        :type resource_group_name: str
        :param vault_name: Name of the vault
        :type vault_name: str
        :param tags: The tags that will be assigned to the key vault.
        :type tags: dict[str, str]
        :param properties: Properties of the vault
        :type properties:
         ~azure.mgmt.keyvault.v2016_10_01.models.VaultPatchProperties
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: Vault or ClientRawResponse if raw=true
        :rtype: ~azure.mgmt.keyvault.v2016_10_01.models.Vault or
         ~msrest.pipeline.ClientRawResponse
        :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
        """
        parameters = models.VaultPatchParameters(tags=tags, properties=properties)

        api_version = "2016-10-01"

        # Construct URL
        url = self.update.metadata['url']
        path_format_arguments = {
            'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
            'vaultName': self._serialize.url("vault_name", vault_name, 'str', pattern=r'^[a-zA-Z0-9-]{3,24}$'),
            'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}
        query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if self.config.generate_client_request_id:
            header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
        if custom_headers:
            header_parameters.update(custom_headers)
        if self.config.accept_language is not None:
            header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')

        # Construct body
        body_content = self._serialize.body(parameters, 'VaultPatchParameters')

        # Construct and send request
        request = self._client.patch(url, query_parameters)
        response = self._client.send(
            request, header_parameters, body_content, stream=False, **operation_config)

        if response.status_code not in [200, 201]:
            exp = CloudError(response)
            exp.request_id = response.headers.get('x-ms-request-id')
            raise exp

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('Vault', response)
        if response.status_code == 201:
            deserialized = self._deserialize('Vault', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized
    update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/vaults/{vaultName}'}

    def delete(
            self, resource_group_name, vault_name, custom_headers=None, raw=False, **operation_config):
        """Deletes the specified Azure key vault.

        :param resource_group_name: The name of the Resource Group to which
         the vault belongs.
        :type resource_group_name: str
        :param vault_name: The name of the vault to delete
        :type vault_name: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: None or ClientRawResponse if raw=true
        :rtype: None or ~msrest.pipeline.ClientRawResponse
        :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
        """
        api_version = "2016-10-01"

        # Construct URL
        url = self.delete.metadata['url']
        path_format_arguments = {
            'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
            'vaultName': self._serialize.url("vault_name", vault_name, 'str'),
            'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}
        query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if self.config.generate_client_request_id:
            header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
        if custom_headers:
            header_parameters.update(custom_headers)
        if self.config.accept_language is not None:
            header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')

        # Construct and send request
        request = self._client.delete(url, query_parameters)
        response = self._client.send(request, header_parameters, stream=False, **operation_config)

        if response.status_code not in [200]:
            exp = CloudError(response)
            exp.request_id = response.headers.get('x-ms-request-id')
            raise exp

        if raw:
            client_raw_response = ClientRawResponse(None, response)
            return client_raw_response
    delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/vaults/{vaultName}'}

    def get(
            self, resource_group_name, vault_name, custom_headers=None, raw=False, **operation_config):
        """Gets the specified Azure key vault.

        :param resource_group_name: The name of the Resource Group to which
         the vault belongs.
        :type resource_group_name: str
        :param vault_name: The name of the vault.
        :type vault_name: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: Vault or ClientRawResponse if raw=true
        :rtype: ~azure.mgmt.keyvault.v2016_10_01.models.Vault or
         ~msrest.pipeline.ClientRawResponse
        :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
        """
        api_version = "2016-10-01"

        # Construct URL
        url = self.get.metadata['url']
        path_format_arguments = {
            'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
            'vaultName': self._serialize.url("vault_name", vault_name, 'str'),
            'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}
        query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if self.config.generate_client_request_id:
            header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
        if custom_headers:
            header_parameters.update(custom_headers)
        if self.config.accept_language is not None:
            header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')

        # Construct and send request
        request = self._client.get(url, query_parameters)
        response = self._client.send(request, header_parameters, stream=False, **operation_config)

        if response.status_code not in [200]:
            exp = CloudError(response)
            exp.request_id = response.headers.get('x-ms-request-id')
            raise exp

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('Vault', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized
    get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/vaults/{vaultName}'}

    def update_access_policy(
            self, resource_group_name, vault_name, operation_kind, properties, custom_headers=None, raw=False, **operation_config):
        """Update access policies in a key vault in the specified subscription.

        :param resource_group_name: The name of the Resource Group to which
         the vault belongs.
        :type resource_group_name: str
        :param vault_name: Name of the vault
        :type vault_name: str
        :param operation_kind: Name of the operation. Possible values include:
         'add', 'replace', 'remove'
        :type operation_kind: str or
         ~azure.mgmt.keyvault.v2016_10_01.models.AccessPolicyUpdateKind
        :param properties: Properties of the access policy
        :type properties:
         ~azure.mgmt.keyvault.v2016_10_01.models.VaultAccessPolicyProperties
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: VaultAccessPolicyParameters or ClientRawResponse if raw=true
        :rtype:
         ~azure.mgmt.keyvault.v2016_10_01.models.VaultAccessPolicyParameters or
         ~msrest.pipeline.ClientRawResponse
        :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
        """
        parameters = models.VaultAccessPolicyParameters(properties=properties)

        api_version = "2016-10-01"

        # Construct URL
        url = self.update_access_policy.metadata['url']
        path_format_arguments = {
            'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
            'vaultName': self._serialize.url("vault_name", vault_name, 'str', pattern=r'^[a-zA-Z0-9-]{3,24}$'),
            'operationKind': self._serialize.url("operation_kind", operation_kind, 'AccessPolicyUpdateKind'),
            'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}
        query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if self.config.generate_client_request_id:
            header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
        if custom_headers:
            header_parameters.update(custom_headers)
        if self.config.accept_language is not None:
            header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')

        # Construct body
        body_content = self._serialize.body(parameters, 'VaultAccessPolicyParameters')

        # Construct and send request
        request = self._client.put(url, query_parameters)
        response = self._client.send(
            request, header_parameters, body_content, stream=False, **operation_config)

        if response.status_code not in [200, 201]:
            exp = CloudError(response)
            exp.request_id = response.headers.get('x-ms-request-id')
            raise exp

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('VaultAccessPolicyParameters', response)
        if response.status_code == 201:
            deserialized = self._deserialize('VaultAccessPolicyParameters', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized
    update_access_policy.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/vaults/{vaultName}/accessPolicies/{operationKind}'}

    def list_by_resource_group(
            self, resource_group_name, top=None, custom_headers=None, raw=False, **operation_config):
        """The List operation gets information about the vaults associated with
        the subscription and within the specified resource group.

        :param resource_group_name: The name of the Resource Group to which
         the vault belongs.
        :type resource_group_name: str
        :param top: Maximum number of results to return.
        :type top: int
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: An iterator like instance of Vault
        :rtype:
         ~azure.mgmt.keyvault.v2016_10_01.models.VaultPaged[~azure.mgmt.keyvault.v2016_10_01.models.Vault]
        :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
        """
        api_version = "2016-10-01"

        def internal_paging(next_link=None, raw=False):

            if not next_link:
                # Construct URL
                url = self.list_by_resource_group.metadata['url']
                path_format_arguments = {
                    'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
                    'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str')
                }
                url = self._client.format_url(url, **path_format_arguments)

                # Construct parameters
                query_parameters = {}
                if top is not None:
                    query_parameters['$top'] = self._serialize.query("top", top, 'int')
                query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')

            else:
                url = next_link
                query_parameters = {}

            # Construct headers
            header_parameters = {}
            header_parameters['Content-Type'] = 'application/json; charset=utf-8'
            if self.config.generate_client_request_id:
                header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
            if custom_headers:
                header_parameters.update(custom_headers)
            if self.config.accept_language is not None:
                header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')

            # Construct and send request
            request = self._client.get(url, query_parameters)
            response = self._client.send(
                request, header_parameters, stream=False, **operation_config)

            if response.status_code not in [200]:
                exp = CloudError(response)
                exp.request_id = response.headers.get('x-ms-request-id')
                raise exp

            return response

        # Deserialize response
        deserialized = models.VaultPaged(internal_paging, self._deserialize.dependencies)

        if raw:
            header_dict = {}
            client_raw_response = models.VaultPaged(internal_paging, self._deserialize.dependencies, header_dict)
            return client_raw_response

        return deserialized
    list_by_resource_group.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/vaults'}

    def list_by_subscription(
            self, top=None, custom_headers=None, raw=False, **operation_config):
        """The List operation gets information about the vaults associated with
        the subscription.

        :param top: Maximum number of results to return.
        :type top: int
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: An iterator like instance of Vault
        :rtype:
         ~azure.mgmt.keyvault.v2016_10_01.models.VaultPaged[~azure.mgmt.keyvault.v2016_10_01.models.Vault]
        :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
        """
        api_version = "2016-10-01"

        def internal_paging(next_link=None, raw=False):

            if not next_link:
                # Construct URL
                url = self.list_by_subscription.metadata['url']
                path_format_arguments = {
                    'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str')
                }
                url = self._client.format_url(url, **path_format_arguments)

                # Construct parameters
                query_parameters = {}
                if top is not None:
                    query_parameters['$top'] = self._serialize.query("top", top, 'int')
                query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')

            else:
                url = next_link
                query_parameters = {}

            # Construct headers
            header_parameters = {}
            header_parameters['Content-Type'] = 'application/json; charset=utf-8'
            if self.config.generate_client_request_id:
                header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
            if custom_headers:
                header_parameters.update(custom_headers)
            if self.config.accept_language is not None:
                header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')

            # Construct and send request
            request = self._client.get(url, query_parameters)
            response = self._client.send(
                request, header_parameters, stream=False, **operation_config)

            if response.status_code not in [200]:
                exp = CloudError(response)
                exp.request_id = response.headers.get('x-ms-request-id')
                raise exp

            return response

        # Deserialize response
        deserialized = models.VaultPaged(internal_paging, self._deserialize.dependencies)

        if raw:
            header_dict = {}
            client_raw_response = models.VaultPaged(internal_paging, self._deserialize.dependencies, header_dict)
            return client_raw_response

        return deserialized
    list_by_subscription.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.KeyVault/vaults'}

    def list_deleted(
            self, custom_headers=None, raw=False, **operation_config):
        """Gets information about the deleted vaults in a subscription.

        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: An iterator like instance of DeletedVault
        :rtype:
         ~azure.mgmt.keyvault.v2016_10_01.models.DeletedVaultPaged[~azure.mgmt.keyvault.v2016_10_01.models.DeletedVault]
        :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
        """
        api_version = "2016-10-01"

        def internal_paging(next_link=None, raw=False):

            if not next_link:
                # Construct URL
                url = self.list_deleted.metadata['url']
                path_format_arguments = {
                    'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str')
                }
                url = self._client.format_url(url, **path_format_arguments)

                # Construct parameters
                query_parameters = {}
                query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')

            else:
                url = next_link
                query_parameters = {}

            # Construct headers
            header_parameters = {}
            header_parameters['Content-Type'] = 'application/json; charset=utf-8'
            if self.config.generate_client_request_id:
                header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
            if custom_headers:
                header_parameters.update(custom_headers)
            if self.config.accept_language is not None:
                header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')

            # Construct and send request
            request = self._client.get(url, query_parameters)
            response = self._client.send(
                request, header_parameters, stream=False, **operation_config)

            if response.status_code not in [200]:
                exp = CloudError(response)
                exp.request_id = response.headers.get('x-ms-request-id')
                raise exp

            return response

        # Deserialize response
        deserialized = models.DeletedVaultPaged(internal_paging, self._deserialize.dependencies)

        if raw:
            header_dict = {}
            client_raw_response = models.DeletedVaultPaged(internal_paging, self._deserialize.dependencies, header_dict)
            return client_raw_response

        return deserialized
    list_deleted.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.KeyVault/deletedVaults'}

    def get_deleted(
            self, vault_name, location, custom_headers=None, raw=False, **operation_config):
        """Gets the deleted Azure key vault.

        :param vault_name: The name of the vault.
        :type vault_name: str
        :param location: The location of the deleted vault.
        :type location: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: DeletedVault or ClientRawResponse if raw=true
        :rtype: ~azure.mgmt.keyvault.v2016_10_01.models.DeletedVault or
         ~msrest.pipeline.ClientRawResponse
        :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
        """
        api_version = "2016-10-01"

        # Construct URL
        url = self.get_deleted.metadata['url']
        path_format_arguments = {
            'vaultName': self._serialize.url("vault_name", vault_name, 'str'),
            'location': self._serialize.url("location", location, 'str'),
            'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}
        query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if self.config.generate_client_request_id:
            header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
        if custom_headers:
            header_parameters.update(custom_headers)
        if self.config.accept_language is not None:
            header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')

        # Construct and send request
        request = self._client.get(url, query_parameters)
        response = self._client.send(request, header_parameters, stream=False, **operation_config)

        if response.status_code not in [200]:
            exp = CloudError(response)
            exp.request_id = response.headers.get('x-ms-request-id')
            raise exp

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('DeletedVault', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized
    get_deleted.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.KeyVault/locations/{location}/deletedVaults/{vaultName}'}

    def _purge_deleted_initial(
            self, vault_name, location, custom_headers=None, raw=False, **operation_config):
        api_version = "2016-10-01"

        # Construct URL
        url = self.purge_deleted.metadata['url']
        path_format_arguments = {
            'vaultName': self._serialize.url("vault_name", vault_name, 'str'),
            'location': self._serialize.url("location", location, 'str'),
            'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}
        query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if self.config.generate_client_request_id:
            header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
        if custom_headers:
            header_parameters.update(custom_headers)
        if self.config.accept_language is not None:
            header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')

        # Construct and send request
        request = self._client.post(url, query_parameters)
        response = self._client.send(request, header_parameters, stream=False, **operation_config)

        if response.status_code not in [200, 202]:
            exp = CloudError(response)
            exp.request_id = response.headers.get('x-ms-request-id')
            raise exp

        if raw:
            client_raw_response = ClientRawResponse(None, response)
            return client_raw_response

    def purge_deleted(
            self, vault_name, location, custom_headers=None, raw=False, polling=True, **operation_config):
        """Permanently deletes the specified vault. aka Purges the deleted Azure
        key vault.

        :param vault_name: The name of the soft-deleted vault.
        :type vault_name: str
        :param location: The location of the soft-deleted vault.
        :type location: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: The poller return type is ClientRawResponse, the
         direct response alongside the deserialized response
        :param polling: True for ARMPolling, False for no polling, or a
         polling object for personal polling strategy
        :return: An instance of LROPoller that returns None or
         ClientRawResponse<None> if raw==True
        :rtype: ~msrestazure.azure_operation.AzureOperationPoller[None] or
         ~msrestazure.azure_operation.AzureOperationPoller[~msrest.pipeline.ClientRawResponse[None]]
        :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
        """
        raw_result = self._purge_deleted_initial(
            vault_name=vault_name,
            location=location,
            custom_headers=custom_headers,
            raw=True,
            **operation_config
        )

        def get_long_running_output(response):
            if raw:
                client_raw_response = ClientRawResponse(None, response)
                return client_raw_response

        lro_delay = operation_config.get(
            'long_running_operation_timeout',
            self.config.long_running_operation_timeout)
        if polling is True: polling_method = ARMPolling(lro_delay, **operation_config)
        elif polling is False: polling_method = NoPolling()
        else: polling_method = polling
        return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
    purge_deleted.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.KeyVault/locations/{location}/deletedVaults/{vaultName}/purge'}

    def list(
            self, top=None, custom_headers=None, raw=False, **operation_config):
        """The List operation gets information about the vaults associated with
        the subscription.

        :param top: Maximum number of results to return.
        :type top: int
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: An iterator like instance of Resource
        :rtype:
         ~azure.mgmt.keyvault.v2016_10_01.models.ResourcePaged[~azure.mgmt.keyvault.v2016_10_01.models.Resource]
        :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
        """
        api_version = "2015-11-01"

        def internal_paging(next_link=None, raw=False):

            if not next_link:
                # Construct URL
                url = self.list.metadata['url']
                path_format_arguments = {
                    'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str')
                }
                url = self._client.format_url(url, **path_format_arguments)

                # Construct parameters
                query_parameters = {}
                query_parameters['$filter'] = self._serialize.query("self.filter", self.filter, 'str')
                if top is not None:
                    query_parameters['$top'] = self._serialize.query("top", top, 'int')
                query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')

            else:
                url = next_link
                query_parameters = {}

            # Construct headers
            header_parameters = {}
            header_parameters['Content-Type'] = 'application/json; charset=utf-8'
            if self.config.generate_client_request_id:
                header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
            if custom_headers:
                header_parameters.update(custom_headers)
            if self.config.accept_language is not None:
                header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')

            # Construct and send request
            request = self._client.get(url, query_parameters)
            response = self._client.send(
                request, header_parameters, stream=False, **operation_config)

            if response.status_code not in [200]:
                exp = CloudError(response)
                exp.request_id = response.headers.get('x-ms-request-id')
                raise exp

            return response

        # Deserialize response
        deserialized = models.ResourcePaged(internal_paging, self._deserialize.dependencies)

        if raw:
            header_dict = {}
            client_raw_response = models.ResourcePaged(internal_paging, self._deserialize.dependencies, header_dict)
            return client_raw_response

        return deserialized
    list.metadata = {'url': '/subscriptions/{subscriptionId}/resources'}

    def check_name_availability(
            self, name, custom_headers=None, raw=False, **operation_config):
        """Checks that the vault name is valid and is not already in use.

        :param name: The vault name.
        :type name: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: CheckNameAvailabilityResult or ClientRawResponse if raw=true
        :rtype:
         ~azure.mgmt.keyvault.v2016_10_01.models.CheckNameAvailabilityResult or
         ~msrest.pipeline.ClientRawResponse
        :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
        """
        vault_name = models.VaultCheckNameAvailabilityParameters(name=name)

        api_version = "2016-10-01"

        # Construct URL
        url = self.check_name_availability.metadata['url']
        path_format_arguments = {
            'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}
        query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if self.config.generate_client_request_id:
            header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
        if custom_headers:
            header_parameters.update(custom_headers)
        if self.config.accept_language is not None:
            header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')

        # Construct body
        body_content = self._serialize.body(vault_name, 'VaultCheckNameAvailabilityParameters')

        # Construct and send request
        request = self._client.post(url, query_parameters)
        response = self._client.send(
            request, header_parameters, body_content, stream=False, **operation_config)

        if response.status_code not in [200]:
            exp = CloudError(response)
            exp.request_id = response.headers.get('x-ms-request-id')
            raise exp

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('CheckNameAvailabilityResult', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized
    check_name_availability.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.KeyVault/checkNameAvailability'}


#---------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
#---------------------------------------------------------------------------------------------

try:
    import urllib.parse as parse
except ImportError:
    import urlparse as parse # pylint: disable=import-error

class HttpChallenge(object):

    def __init__(self, request_uri, challenge, response_headers=None):
        """ Parses an HTTP WWW-Authentication Bearer challenge from a server. """
        self.source_authority = self._validate_request_uri(request_uri)
        self.source_uri = request_uri
        self._parameters = {}

        # get the scheme of the challenge and remove from the challenge string
        trimmed_challenge = self._validate_challenge(challenge)
        split_challenge = trimmed_challenge.split(' ', 1)
        self.scheme = split_challenge[0]
        trimmed_challenge = split_challenge[1]

        # split trimmed challenge into comma-separated name=value pairs. Values are expected
        # to be surrounded by quotes which are stripped here.
        for item in trimmed_challenge.split(','):
            # process name=value pairs
            comps = item.split('=')
            if len(comps) == 2:
                key = comps[0].strip(' "')
                value = comps[1].strip(' "')
                if key:
                    self._parameters[key] = value

        # minimum set of parameters
        if not self._parameters:
            raise ValueError('Invalid challenge parameters')

        # must specify authorization or authorization_uri
        if 'authorization' not in self._parameters and 'authorization_uri' not in self._parameters:
            raise ValueError('Invalid challenge parameters')

        # if the response headers were supplied
        if response_headers:
            # get the message signing key and message key encryption key from the headers
            self.server_signature_key = response_headers.get('x-ms-message-signing-key', None)
            self.server_encryption_key = response_headers.get('x-ms-message-encryption-key', None)

    def is_bearer_challenge(self):
        """ Tests whether the HttpChallenge a Bearer challenge.
        rtype: bool """
        if not self.scheme:
            return False

        return self.scheme.lower() == 'bearer'

    def is_pop_challenge(self):
        """ Tests whether the HttpChallenge is a proof of possession challenge.
        rtype: bool """
        if not self.scheme:
            return False

        return self.scheme.lower() == 'pop'

    def get_value(self, key):
        return self._parameters.get(key)

    def get_authorization_server(self):
        """ Returns the URI for the authorization server if present, otherwise empty string. """
        value = ''
        for key in ['authorization_uri', 'authorization']:
            value = self.get_value(key) or ''
            if value:
                break
        return value

    def get_resource(self):
        """ Returns the resource if present, otherwise empty string. """
        return self.get_value('resource') or ''

    def get_scope(self):
        """ Returns the scope if present, otherwise empty string. """
        return self.get_value('scope') or ''

    def supports_pop(self):
        """ Returns True if challenge supports pop token auth else False """
        return self._parameters.get('supportspop', '').lower() == 'true'

    def supports_message_protection(self):
        """ Returns True if challenge vault supports message protection """
        return self.supports_pop() and self.server_encryption_key and self.server_signature_key

    def _validate_challenge(self, challenge):
        """ Verifies that the challenge is a valid auth challenge and returns the key=value pairs. """
        if not challenge:
            raise ValueError('Challenge cannot be empty')

        return challenge.strip()

    # pylint: disable=no-self-use
    def _validate_request_uri(self, uri):
        """ Extracts the host authority from the given URI. """
        if not uri:
            raise ValueError('request_uri cannot be empty')

        uri = parse.urlparse(uri)
        if not uri.netloc:
            raise ValueError('request_uri must be an absolute URI')

        if uri.scheme.lower() not in ['http', 'https']:
            raise ValueError('request_uri must be HTTP or HTTPS')

        return uri.netloc


#-------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#--------------------------------------------------------------------------

import os.path

def get_cli_profile():
    """Return a CLI profile class.

    .. versionadded:: 1.1.6

    :return: A CLI Profile
    :rtype: azure.cli.core._profile.Profile
    :raises: ImportError if azure-cli-core package is not available
    """

    try:
        from azure.cli.core._profile import Profile
        from azure.cli.core._session import ACCOUNT
        from azure.cli.core._environment import get_config_dir
    except ImportError:
        raise ImportError("You need to install 'azure-cli-core' to load CLI credentials")

    azure_folder = get_config_dir()
    ACCOUNT.load(os.path.join(azure_folder, 'azureProfile.json'))
    return Profile(storage=ACCOUNT)

def get_azure_cli_credentials(resource=None, with_tenant=False):
    """Return Credentials and default SubscriptionID of current loaded profile of the CLI.

    Credentials will be the "az login" command:
    https://docs.microsoft.com/cli/azure/authenticate-azure-cli

    Default subscription ID is either the only one you have, or you can define it:
    https://docs.microsoft.com/cli/azure/manage-azure-subscriptions-azure-cli

    .. versionadded:: 1.1.6

    :param str resource: The alternative resource for credentials if not ARM (GraphRBac, etc.)
    :param bool with_tenant: If True, return a three-tuple with last as tenant ID
    :return: tuple of Credentials and SubscriptionID (and tenant ID if with_tenant)
    :rtype: tuple
    """
    profile = get_cli_profile()
    cred, subscription_id, tenant_id = profile.get_login_credentials(resource=resource)
    if with_tenant:
        return cred, subscription_id, tenant_id
    else:
        return cred, subscription_id

try:
    from msrest.authentication import (
        BasicAuthentication,
        BasicTokenAuthentication,
        OAuthTokenAuthentication
    )
except ImportError:
    raise ImportError("You need to install 'msrest' to use this feature")

try:
    from msrestazure.azure_active_directory import (
        InteractiveCredentials,
        ServicePrincipalCredentials,
        UserPassCredentials
    )
except ImportError:
    raise ImportError("You need to install 'msrestazure' to use this feature")


# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------

import uuid
from msrest.pipeline import ClientRawResponse

from .. import models

class AlertsOperations(object):
    """AlertsOperations operations.

    :param client: Client for service requests.
    :param config: Configuration of service client.
    :param serializer: An object model serializer.
    :param deserializer: An object model deserializer.
    :ivar api_version: API version. Constant value: "2018-05-05".
    """

    models = models

    def __init__(self, client, config, serializer, deserializer):

        self._client = client
        self._serialize = serializer
        self._deserialize = deserializer
        self.api_version = "2018-05-05"

        self.config = config

    def get_all(
            self, target_resource=None, target_resource_type=None, target_resource_group=None, monitor_service=None, monitor_condition=None, severity=None, alert_state=None, alert_rule=None, smart_group_id=None, include_context=None, include_egress_config=None, page_count=None, sort_by=None, sort_order=None, select=None, time_range=None, custom_time_range=None, custom_headers=None, raw=False, **operation_config):
        """List all the existing alerts, where the results can be selective by
        passing multiple filter parameters including time range and sorted on
        specific fields. .

        :param target_resource: Filter by target resource( which is full ARM
         ID) Default value is select all.
        :type target_resource: str
        :param target_resource_type: Filter by target resource type. Default
         value is select all.
        :type target_resource_type: str
        :param target_resource_group: Filter by target resource group name.
         Default value is select all.
        :type target_resource_group: str
        :param monitor_service: Filter by monitor service which is the source
         of the alert instance. Default value is select all. Possible values
         include: 'Application Insights', 'ActivityLog Administrative',
         'ActivityLog Security', 'ActivityLog Recommendation', 'ActivityLog
         Policy', 'ActivityLog Autoscale', 'Log Analytics', 'Nagios',
         'Platform', 'SCOM', 'ServiceHealth', 'SmartDetector', 'VM Insights',
         'Zabbix'
        :type monitor_service: str or
         ~azure.mgmt.alertsmanagement.models.MonitorService
        :param monitor_condition: Filter by monitor condition which is the
         state of the  monitor(alertRule) at monitor service. Default value is
         to select all. Possible values include: 'Fired', 'Resolved'
        :type monitor_condition: str or
         ~azure.mgmt.alertsmanagement.models.MonitorCondition
        :param severity: Filter by severity.  Defaut value is select all.
         Possible values include: 'Sev0', 'Sev1', 'Sev2', 'Sev3', 'Sev4'
        :type severity: str or ~azure.mgmt.alertsmanagement.models.Severity
        :param alert_state: Filter by state of the alert instance. Default
         value is to select all. Possible values include: 'New',
         'Acknowledged', 'Closed'
        :type alert_state: str or
         ~azure.mgmt.alertsmanagement.models.AlertState
        :param alert_rule: Filter by alert rule(monitor) which fired alert
         instance.  Default value is to select all.
        :type alert_rule: str
        :param smart_group_id: Filter the alerts list by the Smart Group Id.
         Default value is none.
        :type smart_group_id: str
        :param include_context: Include context which has data contextual to
         the monitor service. Default value is false'
        :type include_context: bool
        :param include_egress_config: Include egress config which would be
         used for displaying the content in portal.  Default value is 'false'.
        :type include_egress_config: bool
        :param page_count: Determines number of alerts returned per page in
         response. Permissible value is between 1 to 250. When the
         "includeContent"  filter is selected, maximum value allowed is 25.
         Default value is 25.
        :type page_count: int
        :param sort_by: Sort the query results by input field,  Default value
         is 'lastModifiedDateTime'. Possible values include: 'name',
         'severity', 'alertState', 'monitorCondition', 'targetResource',
         'targetResourceName', 'targetResourceGroup', 'targetResourceType',
         'startDateTime', 'lastModifiedDateTime'
        :type sort_by: str or
         ~azure.mgmt.alertsmanagement.models.AlertsSortByFields
        :param sort_order: Sort the query results order in either ascending or
         descending.  Default value is 'desc' for time fields and 'asc' for
         others. Possible values include: 'asc', 'desc'
        :type sort_order: str
        :param select: This filter allows to selection of the fields(comma
         seperated) which would  be part of the the essential section. This
         would allow to project only the  required fields rather than getting
         entire content.  Default is to fetch all the fields in the essentials
         section.
        :type select: str
        :param time_range: Filter by time range by below listed values.
         Default value is 1 day. Possible values include: '1h', '1d', '7d',
         '30d'
        :type time_range: str or ~azure.mgmt.alertsmanagement.models.TimeRange
        :param custom_time_range: Filter by custom time range in the format
         <start-time>/<end-time>  where time is in (ISO-8601 format)'.
         Permissible values is within 30 days from  query time. Either
         timeRange or customTimeRange could be used but not both. Default is
         none.
        :type custom_time_range: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: An iterator like instance of Alert
        :rtype:
         ~azure.mgmt.alertsmanagement.models.AlertPaged[~azure.mgmt.alertsmanagement.models.Alert]
        :raises:
         :class:`ErrorResponseException<azure.mgmt.alertsmanagement.models.ErrorResponseException>`
        """
        def internal_paging(next_link=None, raw=False):

            if not next_link:
                # Construct URL
                url = self.get_all.metadata['url']
                path_format_arguments = {
                    'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str')
                }
                url = self._client.format_url(url, **path_format_arguments)

                # Construct parameters
                query_parameters = {}
                if target_resource is not None:
                    query_parameters['targetResource'] = self._serialize.query("target_resource", target_resource, 'str')
                if target_resource_type is not None:
                    query_parameters['targetResourceType'] = self._serialize.query("target_resource_type", target_resource_type, 'str')
                if target_resource_group is not None:
                    query_parameters['targetResourceGroup'] = self._serialize.query("target_resource_group", target_resource_group, 'str')
                if monitor_service is not None:
                    query_parameters['monitorService'] = self._serialize.query("monitor_service", monitor_service, 'str')
                if monitor_condition is not None:
                    query_parameters['monitorCondition'] = self._serialize.query("monitor_condition", monitor_condition, 'str')
                if severity is not None:
                    query_parameters['severity'] = self._serialize.query("severity", severity, 'str')
                if alert_state is not None:
                    query_parameters['alertState'] = self._serialize.query("alert_state", alert_state, 'str')
                if alert_rule is not None:
                    query_parameters['alertRule'] = self._serialize.query("alert_rule", alert_rule, 'str')
                if smart_group_id is not None:
                    query_parameters['smartGroupId'] = self._serialize.query("smart_group_id", smart_group_id, 'str')
                if include_context is not None:
                    query_parameters['includeContext'] = self._serialize.query("include_context", include_context, 'bool')
                if include_egress_config is not None:
                    query_parameters['includeEgressConfig'] = self._serialize.query("include_egress_config", include_egress_config, 'bool')
                if page_count is not None:
                    query_parameters['pageCount'] = self._serialize.query("page_count", page_count, 'int')
                if sort_by is not None:
                    query_parameters['sortBy'] = self._serialize.query("sort_by", sort_by, 'str')
                if sort_order is not None:
                    query_parameters['sortOrder'] = self._serialize.query("sort_order", sort_order, 'str')
                if select is not None:
                    query_parameters['select'] = self._serialize.query("select", select, 'str')
                if time_range is not None:
                    query_parameters['timeRange'] = self._serialize.query("time_range", time_range, 'str')
                if custom_time_range is not None:
                    query_parameters['customTimeRange'] = self._serialize.query("custom_time_range", custom_time_range, 'str')
                query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str')

            else:
                url = next_link
                query_parameters = {}

            # Construct headers
            header_parameters = {}
            header_parameters['Accept'] = 'application/json'
            if self.config.generate_client_request_id:
                header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
            if custom_headers:
                header_parameters.update(custom_headers)
            if self.config.accept_language is not None:
                header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')

            # Construct and send request
            request = self._client.get(url, query_parameters, header_parameters)
            response = self._client.send(request, stream=False, **operation_config)

            if response.status_code not in [200]:
                raise models.ErrorResponseException(self._deserialize, response)

            return response

        # Deserialize response
        deserialized = models.AlertPaged(internal_paging, self._deserialize.dependencies)

        if raw:
            header_dict = {}
            client_raw_response = models.AlertPaged(internal_paging, self._deserialize.dependencies, header_dict)
            return client_raw_response

        return deserialized
    get_all.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.AlertsManagement/alerts'}

    def get_by_id(
            self, alert_id, custom_headers=None, raw=False, **operation_config):
        """Get a specific alert.

        Get information related to a specific alert.

        :param alert_id: Unique ID of an alert instance.
        :type alert_id: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: Alert or ClientRawResponse if raw=true
        :rtype: ~azure.mgmt.alertsmanagement.models.Alert or
         ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`ErrorResponseException<azure.mgmt.alertsmanagement.models.ErrorResponseException>`
        """
        # Construct URL
        url = self.get_by_id.metadata['url']
        path_format_arguments = {
            'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str'),
            'alertId': self._serialize.url("alert_id", alert_id, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}
        query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str')

        # Construct headers
        header_parameters = {}
        header_parameters['Accept'] = 'application/json'
        if self.config.generate_client_request_id:
            header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
        if custom_headers:
            header_parameters.update(custom_headers)
        if self.config.accept_language is not None:
            header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')

        # Construct and send request
        request = self._client.get(url, query_parameters, header_parameters)
        response = self._client.send(request, stream=False, **operation_config)

        if response.status_code not in [200]:
            raise models.ErrorResponseException(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('Alert', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized
    get_by_id.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.AlertsManagement/alerts/{alertId}'}

    def change_state(
            self, alert_id, new_state, custom_headers=None, raw=False, **operation_config):
        """Change the state of the alert.

        :param alert_id: Unique ID of an alert instance.
        :type alert_id: str
        :param new_state: New state of the alert. Possible values include:
         'New', 'Acknowledged', 'Closed'
        :type new_state: str or ~azure.mgmt.alertsmanagement.models.AlertState
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: Alert or ClientRawResponse if raw=true
        :rtype: ~azure.mgmt.alertsmanagement.models.Alert or
         ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`ErrorResponseException<azure.mgmt.alertsmanagement.models.ErrorResponseException>`
        """
        # Construct URL
        url = self.change_state.metadata['url']
        path_format_arguments = {
            'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str'),
            'alertId': self._serialize.url("alert_id", alert_id, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}
        query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str')
        query_parameters['newState'] = self._serialize.query("new_state", new_state, 'str')

        # Construct headers
        header_parameters = {}
        header_parameters['Accept'] = 'application/json'
        if self.config.generate_client_request_id:
            header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
        if custom_headers:
            header_parameters.update(custom_headers)
        if self.config.accept_language is not None:
            header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')

        # Construct and send request
        request = self._client.post(url, query_parameters, header_parameters)
        response = self._client.send(request, stream=False, **operation_config)

        if response.status_code not in [200]:
            raise models.ErrorResponseException(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('Alert', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized
    change_state.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.AlertsManagement/alerts/{alertId}/changestate'}

    def get_history(
            self, alert_id, custom_headers=None, raw=False, **operation_config):
        """Get the history of the changes of an alert.

        :param alert_id: Unique ID of an alert instance.
        :type alert_id: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: AlertModification or ClientRawResponse if raw=true
        :rtype: ~azure.mgmt.alertsmanagement.models.AlertModification or
         ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`ErrorResponseException<azure.mgmt.alertsmanagement.models.ErrorResponseException>`
        """
        # Construct URL
        url = self.get_history.metadata['url']
        path_format_arguments = {
            'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str'),
            'alertId': self._serialize.url("alert_id", alert_id, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}
        query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str')

        # Construct headers
        header_parameters = {}
        header_parameters['Accept'] = 'application/json'
        if self.config.generate_client_request_id:
            header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
        if custom_headers:
            header_parameters.update(custom_headers)
        if self.config.accept_language is not None:
            header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')

        # Construct and send request
        request = self._client.get(url, query_parameters, header_parameters)
        response = self._client.send(request, stream=False, **operation_config)

        if response.status_code not in [200]:
            raise models.ErrorResponseException(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('AlertModification', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized
    get_history.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.AlertsManagement/alerts/{alertId}/history'}

    def get_summary(
            self, groupby, include_smart_groups_count=None, target_resource=None, target_resource_type=None, target_resource_group=None, monitor_service=None, monitor_condition=None, severity=None, alert_state=None, alert_rule=None, time_range=None, custom_time_range=None, custom_headers=None, raw=False, **operation_config):
        """Summary of alerts with the count each severity.

        :param groupby: This parameter allows the result set to be aggregated
         by input fields. For example, groupby=severity,alertstate. Possible
         values include: 'severity', 'alertState', 'monitorCondition',
         'monitorService', 'signalType', 'alertRule'
        :type groupby: str or
         ~azure.mgmt.alertsmanagement.models.AlertsSummaryGroupByFields
        :param include_smart_groups_count: Include count of the SmartGroups as
         part of the summary. Default value is 'false'.
        :type include_smart_groups_count: bool
        :param target_resource: Filter by target resource( which is full ARM
         ID) Default value is select all.
        :type target_resource: str
        :param target_resource_type: Filter by target resource type. Default
         value is select all.
        :type target_resource_type: str
        :param target_resource_group: Filter by target resource group name.
         Default value is select all.
        :type target_resource_group: str
        :param monitor_service: Filter by monitor service which is the source
         of the alert instance. Default value is select all. Possible values
         include: 'Application Insights', 'ActivityLog Administrative',
         'ActivityLog Security', 'ActivityLog Recommendation', 'ActivityLog
         Policy', 'ActivityLog Autoscale', 'Log Analytics', 'Nagios',
         'Platform', 'SCOM', 'ServiceHealth', 'SmartDetector', 'VM Insights',
         'Zabbix'
        :type monitor_service: str or
         ~azure.mgmt.alertsmanagement.models.MonitorService
        :param monitor_condition: Filter by monitor condition which is the
         state of the  monitor(alertRule) at monitor service. Default value is
         to select all. Possible values include: 'Fired', 'Resolved'
        :type monitor_condition: str or
         ~azure.mgmt.alertsmanagement.models.MonitorCondition
        :param severity: Filter by severity.  Defaut value is select all.
         Possible values include: 'Sev0', 'Sev1', 'Sev2', 'Sev3', 'Sev4'
        :type severity: str or ~azure.mgmt.alertsmanagement.models.Severity
        :param alert_state: Filter by state of the alert instance. Default
         value is to select all. Possible values include: 'New',
         'Acknowledged', 'Closed'
        :type alert_state: str or
         ~azure.mgmt.alertsmanagement.models.AlertState
        :param alert_rule: Filter by alert rule(monitor) which fired alert
         instance.  Default value is to select all.
        :type alert_rule: str
        :param time_range: Filter by time range by below listed values.
         Default value is 1 day. Possible values include: '1h', '1d', '7d',
         '30d'
        :type time_range: str or ~azure.mgmt.alertsmanagement.models.TimeRange
        :param custom_time_range: Filter by custom time range in the format
         <start-time>/<end-time>  where time is in (ISO-8601 format)'.
         Permissible values is within 30 days from  query time. Either
         timeRange or customTimeRange could be used but not both. Default is
         none.
        :type custom_time_range: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: AlertsSummary or ClientRawResponse if raw=true
        :rtype: ~azure.mgmt.alertsmanagement.models.AlertsSummary or
         ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`ErrorResponseException<azure.mgmt.alertsmanagement.models.ErrorResponseException>`
        """
        # Construct URL
        url = self.get_summary.metadata['url']
        path_format_arguments = {
            'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}
        query_parameters['groupby'] = self._serialize.query("groupby", groupby, 'str')
        if include_smart_groups_count is not None:
            query_parameters['includeSmartGroupsCount'] = self._serialize.query("include_smart_groups_count", include_smart_groups_count, 'bool')
        if target_resource is not None:
            query_parameters['targetResource'] = self._serialize.query("target_resource", target_resource, 'str')
        if target_resource_type is not None:
            query_parameters['targetResourceType'] = self._serialize.query("target_resource_type", target_resource_type, 'str')
        if target_resource_group is not None:
            query_parameters['targetResourceGroup'] = self._serialize.query("target_resource_group", target_resource_group, 'str')
        if monitor_service is not None:
            query_parameters['monitorService'] = self._serialize.query("monitor_service", monitor_service, 'str')
        if monitor_condition is not None:
            query_parameters['monitorCondition'] = self._serialize.query("monitor_condition", monitor_condition, 'str')
        if severity is not None:
            query_parameters['severity'] = self._serialize.query("severity", severity, 'str')
        if alert_state is not None:
            query_parameters['alertState'] = self._serialize.query("alert_state", alert_state, 'str')
        if alert_rule is not None:
            query_parameters['alertRule'] = self._serialize.query("alert_rule", alert_rule, 'str')
        if time_range is not None:
            query_parameters['timeRange'] = self._serialize.query("time_range", time_range, 'str')
        if custom_time_range is not None:
            query_parameters['customTimeRange'] = self._serialize.query("custom_time_range", custom_time_range, 'str')
        query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str')

        # Construct headers
        header_parameters = {}
        header_parameters['Accept'] = 'application/json'
        if self.config.generate_client_request_id:
            header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
        if custom_headers:
            header_parameters.update(custom_headers)
        if self.config.accept_language is not None:
            header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')

        # Construct and send request
        request = self._client.get(url, query_parameters, header_parameters)
        response = self._client.send(request, stream=False, **operation_config)

        if response.status_code not in [200]:
            raise models.ErrorResponseException(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('AlertsSummary', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized
    get_summary.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.AlertsManagement/alertsSummary'}