# 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 ManagedDatabasesOperations(object):
    """ManagedDatabasesOperations 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: The API version to use for the request. Constant value: "2017-03-01-preview".
    """

    models = models

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

        self._client = client
        self._serialize = serializer
        self._deserialize = deserializer
        self.api_version = "2017-03-01-preview"

        self.config = config

    def _complete_restore_initial(
            self, location_name, operation_id, last_backup_name, custom_headers=None, raw=False, **operation_config):
        parameters = models.CompleteDatabaseRestoreDefinition(last_backup_name=last_backup_name)

        # Construct URL
        url = self.complete_restore.metadata['url']
        path_format_arguments = {
            'locationName': self._serialize.url("location_name", location_name, 'str'),
            'operationId': self._serialize.url("operation_id", operation_id, '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("self.api_version", self.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, 'CompleteDatabaseRestoreDefinition')

        # Construct and send request
        request = self._client.post(url, query_parameters, header_parameters, body_content)
        response = self._client.send(request, 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 complete_restore(
            self, location_name, operation_id, last_backup_name, custom_headers=None, raw=False, polling=True, **operation_config):
        """Completes the restore operation on a managed database.

        :param location_name: The name of the region where the resource is
         located.
        :type location_name: str
        :param operation_id: Management operation id that this request tries
         to complete.
        :type operation_id: str
        :param last_backup_name: The last backup name to apply
        :type last_backup_name: 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._complete_restore_initial(
            location_name=location_name,
            operation_id=operation_id,
            last_backup_name=last_backup_name,
            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)
    complete_restore.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Sql/locations/{locationName}/managedDatabaseRestoreAzureAsyncOperation/{operationId}/completeRestore'}

    def list_by_instance(
            self, resource_group_name, managed_instance_name, custom_headers=None, raw=False, **operation_config):
        """Gets a list of managed databases.

        :param resource_group_name: The name of the resource group that
         contains the resource. You can obtain this value from the Azure
         Resource Manager API or the portal.
        :type resource_group_name: str
        :param managed_instance_name: The name of the managed instance.
        :type managed_instance_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: An iterator like instance of ManagedDatabase
        :rtype:
         ~azure.mgmt.sql.models.ManagedDatabasePaged[~azure.mgmt.sql.models.ManagedDatabase]
        :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
        """
        def internal_paging(next_link=None, raw=False):

            if not next_link:
                # Construct URL
                url = self.list_by_instance.metadata['url']
                path_format_arguments = {
                    'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
                    'managedInstanceName': self._serialize.url("managed_instance_name", managed_instance_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("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]:
                exp = CloudError(response)
                exp.request_id = response.headers.get('x-ms-request-id')
                raise exp

            return response

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

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

        return deserialized
    list_by_instance.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/managedInstances/{managedInstanceName}/databases'}

    def get(
            self, resource_group_name, managed_instance_name, database_name, custom_headers=None, raw=False, **operation_config):
        """Gets a managed database.

        :param resource_group_name: The name of the resource group that
         contains the resource. You can obtain this value from the Azure
         Resource Manager API or the portal.
        :type resource_group_name: str
        :param managed_instance_name: The name of the managed instance.
        :type managed_instance_name: str
        :param database_name: The name of the database.
        :type database_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: ManagedDatabase or ClientRawResponse if raw=true
        :rtype: ~azure.mgmt.sql.models.ManagedDatabase or
         ~msrest.pipeline.ClientRawResponse
        :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
        """
        # Construct URL
        url = self.get.metadata['url']
        path_format_arguments = {
            'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
            'managedInstanceName': self._serialize.url("managed_instance_name", managed_instance_name, 'str'),
            'databaseName': self._serialize.url("database_name", database_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("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]:
            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('ManagedDatabase', response)

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

        return deserialized
    get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/managedInstances/{managedInstanceName}/databases/{databaseName}'}

    def _create_or_update_initial(
            self, resource_group_name, managed_instance_name, database_name, parameters, custom_headers=None, raw=False, **operation_config):
        # Construct URL
        url = self.create_or_update.metadata['url']
        path_format_arguments = {
            'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
            'managedInstanceName': self._serialize.url("managed_instance_name", managed_instance_name, 'str'),
            'databaseName': self._serialize.url("database_name", database_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("self.api_version", self.api_version, 'str')

        # Construct headers
        header_parameters = {}
        header_parameters['Accept'] = 'application/json'
        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, 'ManagedDatabase')

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

        if response.status_code not in [200, 201, 202]:
            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('ManagedDatabase', response)
        if response.status_code == 201:
            deserialized = self._deserialize('ManagedDatabase', response)

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

        return deserialized

    def create_or_update(
            self, resource_group_name, managed_instance_name, database_name, parameters, custom_headers=None, raw=False, polling=True, **operation_config):
        """Creates a new database or updates an existing database.

        :param resource_group_name: The name of the resource group that
         contains the resource. You can obtain this value from the Azure
         Resource Manager API or the portal.
        :type resource_group_name: str
        :param managed_instance_name: The name of the managed instance.
        :type managed_instance_name: str
        :param database_name: The name of the database.
        :type database_name: str
        :param parameters: The requested database resource state.
        :type parameters: ~azure.mgmt.sql.models.ManagedDatabase
        :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 ManagedDatabase or
         ClientRawResponse<ManagedDatabase> if raw==True
        :rtype:
         ~msrestazure.azure_operation.AzureOperationPoller[~azure.mgmt.sql.models.ManagedDatabase]
         or
         ~msrestazure.azure_operation.AzureOperationPoller[~msrest.pipeline.ClientRawResponse[~azure.mgmt.sql.models.ManagedDatabase]]
        :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
        """
        raw_result = self._create_or_update_initial(
            resource_group_name=resource_group_name,
            managed_instance_name=managed_instance_name,
            database_name=database_name,
            parameters=parameters,
            custom_headers=custom_headers,
            raw=True,
            **operation_config
        )

        def get_long_running_output(response):
            deserialized = self._deserialize('ManagedDatabase', response)

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

            return deserialized

        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)
    create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/managedInstances/{managedInstanceName}/databases/{databaseName}'}

    def _delete_initial(
            self, resource_group_name, managed_instance_name, database_name, custom_headers=None, raw=False, **operation_config):
        # Construct URL
        url = self.delete.metadata['url']
        path_format_arguments = {
            'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
            'managedInstanceName': self._serialize.url("managed_instance_name", managed_instance_name, 'str'),
            'databaseName': self._serialize.url("database_name", database_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("self.api_version", self.api_version, 'str')

        # Construct headers
        header_parameters = {}
        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, header_parameters)
        response = self._client.send(request, stream=False, **operation_config)

        if response.status_code not in [200, 202, 204]:
            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 delete(
            self, resource_group_name, managed_instance_name, database_name, custom_headers=None, raw=False, polling=True, **operation_config):
        """Deletes a managed database.

        :param resource_group_name: The name of the resource group that
         contains the resource. You can obtain this value from the Azure
         Resource Manager API or the portal.
        :type resource_group_name: str
        :param managed_instance_name: The name of the managed instance.
        :type managed_instance_name: str
        :param database_name: The name of the database.
        :type database_name: 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._delete_initial(
            resource_group_name=resource_group_name,
            managed_instance_name=managed_instance_name,
            database_name=database_name,
            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)
    delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/managedInstances/{managedInstanceName}/databases/{databaseName}'}

    def _update_initial(
            self, resource_group_name, managed_instance_name, database_name, parameters, custom_headers=None, raw=False, **operation_config):
        # Construct URL
        url = self.update.metadata['url']
        path_format_arguments = {
            'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
            'managedInstanceName': self._serialize.url("managed_instance_name", managed_instance_name, 'str'),
            'databaseName': self._serialize.url("database_name", database_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("self.api_version", self.api_version, 'str')

        # Construct headers
        header_parameters = {}
        header_parameters['Accept'] = 'application/json'
        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, 'ManagedDatabaseUpdate')

        # Construct and send request
        request = self._client.patch(url, query_parameters, header_parameters, body_content)
        response = self._client.send(request, 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

        deserialized = None

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

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

        return deserialized

    def update(
            self, resource_group_name, managed_instance_name, database_name, parameters, custom_headers=None, raw=False, polling=True, **operation_config):
        """Updates an existing database.

        :param resource_group_name: The name of the resource group that
         contains the resource. You can obtain this value from the Azure
         Resource Manager API or the portal.
        :type resource_group_name: str
        :param managed_instance_name: The name of the managed instance.
        :type managed_instance_name: str
        :param database_name: The name of the database.
        :type database_name: str
        :param parameters: The requested database resource state.
        :type parameters: ~azure.mgmt.sql.models.ManagedDatabaseUpdate
        :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 ManagedDatabase or
         ClientRawResponse<ManagedDatabase> if raw==True
        :rtype:
         ~msrestazure.azure_operation.AzureOperationPoller[~azure.mgmt.sql.models.ManagedDatabase]
         or
         ~msrestazure.azure_operation.AzureOperationPoller[~msrest.pipeline.ClientRawResponse[~azure.mgmt.sql.models.ManagedDatabase]]
        :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
        """
        raw_result = self._update_initial(
            resource_group_name=resource_group_name,
            managed_instance_name=managed_instance_name,
            database_name=database_name,
            parameters=parameters,
            custom_headers=custom_headers,
            raw=True,
            **operation_config
        )

        def get_long_running_output(response):
            deserialized = self._deserialize('ManagedDatabase', response)

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

            return deserialized

        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)
    update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/managedInstances/{managedInstanceName}/databases/{databaseName}'}


# 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 import AzureConfiguration
from msrestazure.azure_active_directory import BasicTokenAuthentication

from azure.profiles import KnownProfiles, ProfileDefinition
from azure.profiles.multiapiclient import MultiApiClientMixin
from .version import VERSION
from . import KeyVaultAuthentication

from azure.keyvault.v7_0.version import VERSION as v7_0_VERSION
from azure.keyvault.v2016_10_01.version import VERSION as v2016_10_01_VERSION

class KeyVaultClientConfiguration(AzureConfiguration):
    """Configuration for KeyVaultClient
    Note that all parameters used to create this instance are saved as instance
    attributes.

    :param credentials: Credentials needed for the client to connect to Azure.
    :type credentials: :mod:`A msrestazure Credentials
     object<msrestazure.azure_active_directory>`
    """

    def __init__(
            self, credentials):

        if credentials is None:
            raise ValueError("Parameter 'credentials' must not be None.")
        base_url = '{vaultBaseUrl}'

        super(KeyVaultClientConfiguration, self).__init__(base_url)

        self.add_user_agent('azure-keyvault/{}'.format(VERSION))
        self.add_user_agent('Azure-SDK-For-Python')

        self.credentials = credentials

class KeyVaultClient(MultiApiClientMixin):
    """The key vault client performs cryptographic key operations and vault operations against the Key Vault service.
    Implementation depends on the API version:

         * 2016-10-01: :class:`v2016_10_01.KeyVaultClient<azure.keyvault.v2016_10_01.KeyVaultClient>`
         * 7.0: :class:`v7_0.KeyVaultClient<azure.mgmt.keyvault.v7_0.KeyVaultClient>`

    :ivar config: Configuration for client.
    :vartype config: KeyVaultClientConfiguration

    :param credentials: Credentials needed for the client to connect to Azure.
    :type credentials: :mod:`A msrestazure Credentials
     object<msrestazure.azure_active_directory>`

    :param str api_version: API version to use if no profile is provided, or if
     missing in profile.
    :param profile: A profile definition, from KnownProfiles to dict.
    :type profile: azure.profiles.KnownProfiles
    """

    DEFAULT_API_VERSION = '7.0'
    _PROFILE_TAG = "azure.keyvault.KeyVaultClient"
    LATEST_PROFILE = ProfileDefinition({
        _PROFILE_TAG: {
            None: DEFAULT_API_VERSION
        }},
        _PROFILE_TAG + " latest"
    )

    _init_complete = False
    def __init__(self, credentials, api_version=None, profile=KnownProfiles.default):
        self.config = KeyVaultClientConfiguration(credentials)
        self._client_impls = {}
        self._entered = False
        super(KeyVaultClient, self).__init__(
            api_version=api_version,
            profile=profile
        )

        # if the supplied credentials instance is not derived from KeyVaultAuthBase but is an AAD credential type
        if not isinstance(credentials, KeyVaultAuthentication) and isinstance(credentials, BasicTokenAuthentication):

            # wrap the supplied credentials with a KeyVaultAuthentication instance. Use that for the credentials
            # supplied to the base client
            credentials = KeyVaultAuthentication(credentials=credentials)

        self._credentials = credentials
        self._init_complete = True

    @property
    def models(self):
        """Module depends on the API version:
            * 2016-10-01: :mod:`v2016_10_01.models<azure.keyvault.v2016_10_01.models>`
            * 7.0: :mod:`v7_0.models<azure.keyvault.v7_0.models>`
         """
        api_version = self._get_api_version(None)

        if api_version == v7_0_VERSION:
            from azure.keyvault.v7_0 import models as implModels
        elif api_version == v2016_10_01_VERSION:
            from azure.keyvault.v2016_10_01 import models as implModels
        else:
            raise NotImplementedError("APIVersion {} is not available".format(api_version))
        return implModels

    def _get_client_impl(self):
        """
        Get the versioned client implementation corresponding to the current profile.
        :return:  The versioned client implementation.
        """
        api_version = self._get_api_version(None)
        if api_version not in self._client_impls:
            self._create_client_impl(api_version)
        return self._client_impls[api_version]

    def _create_client_impl(self, api_version):
        """
        Creates the client implementation corresponding to the specifeid api_version.
        :param api_version:
        :return:
        """
        if api_version == v7_0_VERSION:
            from azure.keyvault.v7_0 import KeyVaultClient as ImplClient
        elif api_version == v2016_10_01_VERSION:
            from azure.keyvault.v2016_10_01 import KeyVaultClient as ImplClient
        else:
            raise NotImplementedError("APIVersion {} is not available".format(api_version))

        impl = ImplClient(credentials=self._credentials)
        impl.config = self.config

        # if __enter__ has previously been called and the impl client has __enter__ defined we need to call it
        if self._entered and hasattr(impl, '__enter__'):
            impl.__enter__()

        self._client_impls[api_version] = impl
        return impl

    def __enter__(self, *args, **kwargs):
        """
        Calls __enter__ on all client implementations which support it
        :param args: positional arguments to relay to client implementations of __enter__
        :param kwargs: keyword arguments to relay to client implementations of __enter__
        :return: returns the current KeyVaultClient instance
        """
        for _, impl in self._client_impls.items():
            if hasattr(impl, '__enter__'):
                impl.__enter__(*args, **kwargs)
        # mark the current KeyVaultClient as _entered so that client implementations instantiated
        # subsequently will also have __enter__ called on them as appropriate
        self._entered = True
        return self

    def __exit__(self, *args, **kwargs):
        """
        Calls __exit__ on all client implementations which support it
        :param args: positional arguments to relay to client implementations of __enter__
        :param kwargs: keyword arguments to relay to client implementations of __enter__
        :return: returns the current KeyVaultClient instance
        """
        for _, impl in self._client_impls.items():
            if hasattr(impl, '__exit__'):
                impl.__exit__(*args, **kwargs)
        return self

    def __getattr__(self, name):
        """
        In the case that the attribute is not defined on the custom KeyVaultClient.  Attempt to get
        the attribute from the versioned client implementation corresponding to the current profile.
        :param name: Name of the attribute retrieve from the current versioned client implementation
        :return: The value of the specified attribute on the current client implementation.
        """
        impl = self._get_client_impl()
        return getattr(impl, name)

    def __setattr__(self, name, attr):
        """
        Sets the specified attribute either on the custom KeyVaultClient or the current underlying implementation.
        :param name: Name of the attribute to set
        :param attr: Value of the attribute to set
        :return: None
        """
        if self._init_complete and not hasattr(self, name):
            impl = self._get_client_impl()
            setattr(impl, name, attr)
        else:
            super(KeyVaultClient, self).__setattr__(name, attr)

    def get_pending_certificate_signing_request(self, vault_base_url, certificate_name, custom_headers=None, raw=False, **operation_config):
        """Gets the Base64 pending certificate signing request (PKCS-10).

        :param vault_base_url: The vault name, e.g.
         https://myvault.vault.azure.net
        :type vault_base_url: str
        :param certificate_name: The name of the certificate
        :type certificate_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: Base64 encoded pending certificate signing request (PKCS-10).
        :rtype: str
        :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
         if raw=true
        """
        # Construct URL
        url = '/certificates/{certificate-name}/pending'
        path_format_arguments = {
            'vaultBaseUrl': self._serialize.url("vault_base_url", vault_base_url, 'str', skip_quote=True),
            'certificate-name': self._serialize.url("certificate_name", certificate_name, '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/pkcs10'
        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=True, **operation_config)

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

        deserialized = None

        if response.status_code == 200:
            deserialized = response.body() if hasattr(response, 'body') else response.content

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

        return deserialized


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

from uamqp import SendClientAsync
from uamqp import authentication
from uamqp import constants, types

from azure.servicebus.common.errors import MessageSendFailed
from azure.servicebus.common import mgmt_handlers, mixins
from azure.servicebus.common.message import Message
from azure.servicebus.common.constants import (
    REQUEST_RESPONSE_SCHEDULE_MESSAGE_OPERATION,
    REQUEST_RESPONSE_CANCEL_SCHEDULED_MESSAGE_OPERATION)
from azure.servicebus.aio.async_base_handler import BaseHandler

class Sender(BaseHandler, mixins.SenderMixin):
    """This handler is for sending messages to a Service Bus entity.

    It operates a single connection that must be opened and closed on completion.
    The Sender can be run within a context manager to ensure that the connection is closed on exit.
    The Sender should not be instantiated directly, and should be accessed from a `QueueClient` or
    `TopicClient` using the `get_sender()` method.

    .. note:: This object is not thread-safe.

    :param handler_id: The ID used as the connection name for the Sender.
    :type handler_id: str
    :param target: The endpoint to send messages to.
    :type target: ~uamqp.Target
    :param auth_config: The SASL auth credentials.
    :type auth_config: dict[str, str]
    :param session: An optional session ID. If supplied, all outgoing messages will have this
     session ID added (unless they already have one specified).
    :type session: str
    :param loop: An async event loop
    :type loop: ~asyncio.EventLoop
    :param connection: A shared connection [not yet supported].
    :type connection: ~uamqp.Connection
    :param encoding: The encoding used for string properties. Default is 'UTF-8'.
    :type encoding: str
    :param debug: Whether to enable network trace debug logs.
    :type debug: bool

    """

    def __init__(
            self, handler_id, target, auth_config, *, session=None, loop=None,
            connection=None, encoding='UTF-8', debug=False, **kwargs):
        self.name = "SBSender-{}".format(handler_id)
        self.session_id = session
        super(Sender, self).__init__(
            target, auth_config, loop=loop, connection=connection, encoding=encoding, debug=debug, **kwargs)

    def _build_handler(self):
        auth = None if self.connection else authentication.SASTokenAsync.from_shared_access_key(**self.auth_config)
        self._handler = SendClientAsync(
            self.endpoint,
            auth=auth,
            debug=self.debug,
            properties=self.properties,
            error_policy=self.error_policy,
            client_name=self.name,
            encoding=self.encoding,
            loop=self.loop,
            **self.handler_kwargs)

    async def send(self, message):
        """Send a message and blocks until acknowledgement is received or the operation fails.

        :param message: The message to be sent.
        :type message: ~azure.servicebus.aio.async_message.Message
        :raises: ~azure.servicebus.common.errors.MessageSendFailed if the message fails to
         send.

        Example:
            .. literalinclude:: ../examples/async_examples/test_examples_async.py
                :start-after: [START open_close_sender_context]
                :end-before: [END open_close_sender_context]
                :language: python
                :dedent: 4
                :caption: Open a Sender and send messages.

        """
        if not isinstance(message, Message):
            raise TypeError("Value of message must be of type 'Message'.")
        if not self.running:
            await self.open()
        if self.session_id and not message.properties.group_id:
            message.properties.group_id = self.session_id
        try:
            await self._handler.send_message_async(message.message)
        except Exception as e:  # pylint: disable=broad-except
            raise MessageSendFailed(e)

    async def schedule(self, schedule_time, *messages):
        """Send one or more messages to be enqueued at a specific time.

        Returns a list of the sequence numbers of the enqueued messages.

        :param schedule_time: The date and time to enqueue the messages.
        :type schedule_time: ~datetime.datetime
        :param messages: The messages to schedule.
        :type messages: ~azure.servicebus.aio.async_message.Message
        :rtype: list[int]

        Example:
            .. literalinclude:: ../examples/async_examples/test_examples_async.py
                :start-after: [START schedule_messages]
                :end-before: [END schedule_messages]
                :language: python
                :dedent: 4
                :caption: Schedule messages.

        """
        if not self.running:
            await self.open()
        request_body = self._build_schedule_request(schedule_time, *messages)
        return await self._mgmt_request_response(
            REQUEST_RESPONSE_SCHEDULE_MESSAGE_OPERATION,
            request_body,
            mgmt_handlers.schedule_op)

    async def cancel_scheduled_messages(self, *sequence_numbers):
        """Cancel one or more messages that have previsouly been scheduled and are still pending.

        :param sequence_numbers: The seqeuence numbers of the scheduled messages.
        :type sequence_numbers: int

        Example:
            .. literalinclude:: ../examples/async_examples/test_examples_async.py
                :start-after: [START cancel_schedule_messages]
                :end-before: [END cancel_schedule_messages]
                :language: python
                :dedent: 4
                :caption: Schedule messages.

        """
        if not self.running:
            await self.open()
        numbers = [types.AMQPLong(s) for s in sequence_numbers]
        request_body = {'sequence-numbers': types.AMQPArray(numbers)}
        return await self._mgmt_request_response(
            REQUEST_RESPONSE_CANCEL_SCHEDULED_MESSAGE_OPERATION,
            request_body,
            mgmt_handlers.default)

    async def send_pending_messages(self):
        """Wait until all pending messages have been sent.

        :returns: A list of the send results of all the pending messages. Each
         send result is a tuple with two values. The first is a boolean, indicating `True`
         if the message sent, or `False` if it failed. The second is an error if the message
         failed, otherwise it will be `None`.
        :rtype: list[tuple[bool, ~azure.servicebus.common.errors.MessageSendFailed]]

        Example:
            .. literalinclude:: ../examples/async_examples/test_examples_async.py
                :start-after: [START queue_sender_messages]
                :end-before: [END queue_sender_messages]
                :language: python
                :dedent: 4
                :caption: Schedule messages.

        """
        if not self.running:
            await self.open()
        try:
            pending = self._handler._pending_messages[:]  # pylint: disable=protected-access
            await self._handler.wait_async()
            results = []
            for m in pending:
                if m.state == constants.MessageState.SendFailed:
                    results.append((False, MessageSendFailed(m._response)))  # pylint: disable=protected-access
                else:
                    results.append((True, None))
            return results
        except Exception as e:  # pylint: disable=broad-except
            raise MessageSendFailed(e)

    async def reconnect(self):
        """Reconnect the handler.

        If the handler was disconnected from the service with
        a retryable error - attempt to reconnect.
        This method will be called automatically for most retryable errors.
        Also attempts to re-queue any messages that were pending before the reconnect.
        """
        unsent_events = self._handler.pending_messages
        await super(Sender, self).reconnect()
        try:
            self._handler.queue_message(*unsent_events)
            await self._handler.wait_async()
        except Exception as e:  # pylint: disable=broad-except
            await self._handle_exception(e)

class SessionSender(Sender):
    """This handler is for sending messages to a sessionful Service Bus entity.

    It operates a single connection that must be opened and closed on completion.
    The Sender can be run within a context manager to ensure that the connection is closed on exit.
    The Sender should not be instantiated directly, and should be accessed from a `QueueClient` or
    `TopicClient` using the `get_sender()` method.
    An attempt to send a message without a session ID specified either on the Sender or the message
    will raise a `ValueError`.

    .. note:: This object is not thread-safe.

    :param handler_id: The ID used as the connection name for the Sender.
    :type handler_id: str
    :param target: The endpoint to send messages to.
    :type target: ~uamqp.Target
    :param auth_config: The SASL auth credentials.
    :type auth_config: dict[str, str]
    :param session: An optional session ID. If supplied, all outgoing messages will have this
     session ID added (unless they already have one specified).
    :type session: str
    :param loop: An async event loop
    :type loop: ~asyncio.EventLoop
    :param connection: A shared connection [not yet supported].
    :type connection: ~uamqp.Connection
    :param encoding: The encoding used for string properties. Default is 'UTF-8'.
    :type encoding: str
    :param debug: Whether to enable network trace debug logs.
    :type debug: bool

    """

    async def send(self, message):
        """Send a message and blocks until acknowledgement is received or the operation fails.

        If neither the Sender nor the message has a session ID, a `ValueError` will be raised.

        :param message: The message to be sent.
        :type message: ~azure.servicebus.aio.async_message.Message
        :raises: ~azure.servicebus.common.errors.MessageSendFailed if the message fails to
         send.

        Example:
            .. literalinclude:: ../examples/async_examples/test_examples_async.py
                :start-after: [START open_close_session_sender_context]
                :end-before: [END open_close_session_sender_context]
                :language: python
                :dedent: 4
                :caption: Open a sessionful Sender and send messages.

        """
        if not isinstance(message, Message):
            raise TypeError("Value of message must be of type 'Message'.")
        if not self.session_id and not message.properties.group_id:
            raise ValueError("Message must have Session ID.")
        return await super(SessionSender, self).send(message)

    def queue_message(self, message):
        """Queue a message to be sent later.

        This operation should be followed up with send_pending_messages. If neither the
        Sender nor the message has a session ID, a `ValueError` will be raised.

        :param message: The message to be sent.
        :type message: ~azure.servicebus.aio.async_message.Message

        Example:
            .. literalinclude:: ../examples/async_examples/test_examples_async.py
                :start-after: [START queue_session_sender_messages]
                :end-before: [END queue_session_sender_messages]
                :language: python
                :dedent: 4
                :caption: Schedule messages.

        """
        if not self.session_id and not message.properties.group_id:
            raise ValueError("Message must have Session ID.")
        super(SessionSender, self).queue_message(message)

    async def schedule_messages(self, schedule_time, *messages):
        """Send one or more messages to be enqueued at a specific time.

        Returns a list of the sequence numbers of the enqueued messages.
        If neither the Sender nor the message has a session ID, a `ValueError` will be raised.

        :param schedule_time: The date and time to enqueue the messages.
        :type schedule_time: ~datetime.datetime
        :param messages: The messages to schedule.
        :type messages: ~azure.servicebus.aio.async_message.Message
        :rtype: list[int]

        Example:
            .. literalinclude:: ../examples/async_examples/test_examples_async.py
                :start-after: [START schedule_session_messages]
                :end-before: [END schedule_session_messages]
                :language: python
                :dedent: 4
                :caption: Schedule messages.

        """
        for message in messages:
            if not self.session_id and not message.properties.group_id:
                raise ValueError("Message must have Session ID.")
        return await super(SessionSender, self).schedule(schedule_time, *messages)


#-------------------------------------------------------------------------
# Copyright (c) Microsoft.  All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#--------------------------------------------------------------------------
from ._common_error import (
    _validate_not_none,
)
from ._common_conversion import (
    _decode_base64_to_bytes,
)

def get_certificate_from_publish_settings(publish_settings_path, path_to_write_certificate, subscription_id=None):
    '''
    Writes a certificate file to the specified location.  This can then be used
    to instantiate ServiceManagementService.  Returns the subscription ID.

    publish_settings_path:
        Path to subscription file downloaded from
        http://go.microsoft.com/fwlink/?LinkID=301775
    path_to_write_certificate:
        Path to write the certificate file.
    subscription_id:
        (optional)  Provide a subscription id here if you wish to use a
        specific subscription under the publish settings file.
    '''
    import base64

    try:
        from xml.etree import cElementTree as ET
    except ImportError:
        from xml.etree import ElementTree as ET

    try:
        import OpenSSL.crypto as crypto
    except:
        raise Exception("pyopenssl is required to use get_certificate_from_publish_settings")

    _validate_not_none('publish_settings_path', publish_settings_path)
    _validate_not_none('path_to_write_certificate', path_to_write_certificate)

    # parse the publishsettings file and find the ManagementCertificate Entry
    tree = ET.parse(publish_settings_path)
    subscriptions = tree.getroot().findall("./PublishProfile/Subscription")

    # Default to the first subscription in the file if they don't specify
    # or get the matching subscription or return none.
    if subscription_id:
        subscription = next((s for s in subscriptions if s.get('Id').lower() == subscription_id.lower()), None)
    else:
        subscription = subscriptions[0]

    # validate that subscription was found
    if subscription is None:
        raise ValueError("The provided subscription_id '{}' was not found in the publish settings file provided at '{}'".format(subscription_id, publish_settings_path))

    cert_string = _decode_base64_to_bytes(subscription.get('ManagementCertificate'))

    # Load the string in pkcs12 format.  Don't provide a password as it isn't encrypted.
    cert = crypto.load_pkcs12(cert_string, b'')

    # Write the data out as a PEM format to a random location in temp for use under this run.
    with open(path_to_write_certificate, 'wb') as f:
        f.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert.get_certificate()))
        f.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, cert.get_privatekey()))

    return subscription.get('Id')


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

from msrest.pipeline import ClientRawResponse

from .. import models

class WebOperations(object):
    """WebOperations 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 x_bing_apis_sdk: Activate swagger compliance. Constant value: "true".
    """

    models = models

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

        self._client = client
        self._serialize = serializer
        self._deserialize = deserializer

        self.config = config
        self.x_bing_apis_sdk = "true"

    def search(
            self, query, accept_language=None, pragma=None, user_agent=None, client_id=None, client_ip=None, location=None, answer_count=None, country_code=None, count=None, freshness=None, market="en-us", offset=None, promote=None, response_filter=None, safe_search=None, set_lang=None, text_decorations=None, text_format=None, custom_headers=None, raw=False, **operation_config):
        """The Web Search API lets you send a search query to Bing and get back
        search results that include links to webpages, images, and more.

        :param query: The user's search query term. The term may not be empty.
         The term may contain Bing Advanced Operators. For example, to limit
         results to a specific domain, use the site: operator.
        :type query: str
        :param accept_language: A comma-delimited list of one or more
         languages to use for user interface strings. The list is in decreasing
         order of preference. For additional information, including expected
         format, see
         [RFC2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html).
         This header and the setLang query parameter are mutually exclusive; do
         not specify both. If you set this header, you must also specify the cc
         query parameter. Bing will use the first supported language it finds
         from the list, and combine that language with the cc parameter value
         to determine the market to return results for. If the list does not
         include a supported language, Bing will find the closest language and
         market that supports the request, and may use an aggregated or default
         market for the results instead of a specified one. You should use this
         header and the cc query parameter only if you specify multiple
         languages; otherwise, you should use the mkt and setLang query
         parameters. A user interface string is a string that's used as a label
         in a user interface. There are very few user interface strings in the
         JSON response objects. Any links in the response objects to Bing.com
         properties will apply the specified language.
        :type accept_language: str
        :param pragma: By default, Bing returns cached content, if available.
         To prevent Bing from returning cached content, set the Pragma header
         to no-cache (for example, Pragma: no-cache).
        :type pragma: str
        :param user_agent: The user agent originating the request. Bing uses
         the user agent to provide mobile users with an optimized experience.
         Although optional, you are strongly encouraged to always specify this
         header. The user-agent should be the same string that any commonly
         used browser would send. For information about user agents, see [RFC
         2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html).
        :type user_agent: str
        :param client_id: Bing uses this header to provide users with
         consistent behavior across Bing API calls. Bing often flights new
         features and improvements, and it uses the client ID as a key for
         assigning traffic on different flights. If you do not use the same
         client ID for a user across multiple requests, then Bing may assign
         the user to multiple conflicting flights. Being assigned to multiple
         conflicting flights can lead to an inconsistent user experience. For
         example, if the second request has a different flight assignment than
         the first, the experience may be unexpected. Also, Bing can use the
         client ID to tailor web results to that client ID’s search history,
         providing a richer experience for the user. Bing also uses this header
         to help improve result rankings by analyzing the activity generated by
         a client ID. The relevance improvements help with better quality of
         results delivered by Bing APIs and in turn enables higher
         click-through rates for the API consumer. IMPORTANT: Although
         optional, you should consider this header required. Persisting the
         client ID across multiple requests for the same end user and device
         combination enables 1) the API consumer to receive a consistent user
         experience, and 2) higher click-through rates via better quality of
         results from the Bing APIs. Each user that uses your application on
         the device must have a unique, Bing generated client ID. If you do not
         include this header in the request, Bing generates an ID and returns
         it in the X-MSEdge-ClientID response header. The only time that you
         should NOT include this header in a request is the first time the user
         uses your app on that device. Use the client ID for each Bing API
         request that your app makes for this user on the device. Persist the
         client ID. To persist the ID in a browser app, use a persistent HTTP
         cookie to ensure the ID is used across all sessions. Do not use a
         session cookie. For other apps such as mobile apps, use the device's
         persistent storage to persist the ID. The next time the user uses your
         app on that device, get the client ID that you persisted. Bing
         responses may or may not include this header. If the response includes
         this header, capture the client ID and use it for all subsequent Bing
         requests for the user on that device. If you include the
         X-MSEdge-ClientID, you must not include cookies in the request.
        :type client_id: str
        :param client_ip: The IPv4 or IPv6 address of the client device. The
         IP address is used to discover the user's location. Bing uses the
         location information to determine safe search behavior. Although
         optional, you are encouraged to always specify this header and the
         X-Search-Location header. Do not obfuscate the address (for example,
         by changing the last octet to 0). Obfuscating the address results in
         the location not being anywhere near the device's actual location,
         which may result in Bing serving erroneous results.
        :type client_ip: str
        :param location: A semicolon-delimited list of key/value pairs that
         describe the client's geographical location. Bing uses the location
         information to determine safe search behavior and to return relevant
         local content. Specify the key/value pair as <key>:<value>. The
         following are the keys that you use to specify the user's location.
         lat (required): The latitude of the client's location, in degrees. The
         latitude must be greater than or equal to -90.0 and less than or equal
         to +90.0. Negative values indicate southern latitudes and positive
         values indicate northern latitudes. long (required): The longitude of
         the client's location, in degrees. The longitude must be greater than
         or equal to -180.0 and less than or equal to +180.0. Negative values
         indicate western longitudes and positive values indicate eastern
         longitudes. re (required): The radius, in meters, which specifies the
         horizontal accuracy of the coordinates. Pass the value returned by the
         device's location service. Typical values might be 22m for GPS/Wi-Fi,
         380m for cell tower triangulation, and 18,000m for reverse IP lookup.
         ts (optional): The UTC UNIX timestamp of when the client was at the
         location. (The UNIX timestamp is the number of seconds since January
         1, 1970.) head (optional): The client's relative heading or direction
         of travel. Specify the direction of travel as degrees from 0 through
         360, counting clockwise relative to true north. Specify this key only
         if the sp key is nonzero. sp (optional): The horizontal velocity
         (speed), in meters per second, that the client device is traveling.
         alt (optional): The altitude of the client device, in meters. are
         (optional): The radius, in meters, that specifies the vertical
         accuracy of the coordinates. Specify this key only if you specify the
         alt key. Although many of the keys are optional, the more information
         that you provide, the more accurate the location results are. Although
         optional, you are encouraged to always specify the user's geographical
         location. Providing the location is especially important if the
         client's IP address does not accurately reflect the user's physical
         location (for example, if the client uses VPN). For optimal results,
         you should include this header and the X-MSEdge-ClientIP header, but
         at a minimum, you should include this header.
        :type location: str
        :param answer_count: The number of answers that you want the response
         to include. The answers that Bing returns are based on ranking. For
         example, if Bing returns webpages, images, videos, and relatedSearches
         for a request and you set this parameter to two (2), the response
         includes webpages and images.If you included the responseFilter query
         parameter in the same request and set it to webpages and news, the
         response would include only webpages.
        :type answer_count: int
        :param country_code: A 2-character country code of the country where
         the results come from. This API supports only the United States
         market. If you specify this query parameter, it must be set to us. If
         you set this parameter, you must also specify the Accept-Language
         header. Bing uses the first supported language it finds from the
         languages list, and combine that language with the country code that
         you specify to determine the market to return results for. If the
         languages list does not include a supported language, Bing finds the
         closest language and market that supports the request, or it may use
         an aggregated or default market for the results instead of a specified
         one. You should use this query parameter and the Accept-Language query
         parameter only if you specify multiple languages; otherwise, you
         should use the mkt and setLang query parameters. This parameter and
         the mkt query parameter are mutually exclusive—do not specify both.
        :type country_code: str
        :param count: The number of search results to return in the response.
         The default is 10 and the maximum value is 50. The actual number
         delivered may be less than requested.Use this parameter along with the
         offset parameter to page results.For example, if your user interface
         displays 10 search results per page, set count to 10 and offset to 0
         to get the first page of results. For each subsequent page, increment
         offset by 10 (for example, 0, 10, 20). It is possible for multiple
         pages to include some overlap in results.
        :type count: int
        :param freshness: Filter search results by the following age values:
         Day—Return webpages that Bing discovered within the last 24 hours.
         Week—Return webpages that Bing discovered within the last 7 days.
         Month—Return webpages that discovered within the last 30 days. This
         filter applies only to webpage results and not to the other results
         such as news and images. Possible values include: 'Day', 'Week',
         'Month'
        :type freshness: str or
         ~azure.cognitiveservices.search.websearch.models.Freshness
        :param market: The market where the results come from. Typically, mkt
         is the country where the user is making the request from. However, it
         could be a different country if the user is not located in a country
         where Bing delivers results. The market must be in the form <language
         code>-<country code>. For example, en-US. The string is case
         insensitive. If known, you are encouraged to always specify the
         market. Specifying the market helps Bing route the request and return
         an appropriate and optimal response. If you specify a market that is
         not listed in Market Codes, Bing uses a best fit market code based on
         an internal mapping that is subject to change. This parameter and the
         cc query parameter are mutually exclusive—do not specify both.
        :type market: str
        :param offset: The zero-based offset that indicates the number of
         search results to skip before returning results. The default is 0. The
         offset should be less than (totalEstimatedMatches - count). Use this
         parameter along with the count parameter to page results. For example,
         if your user interface displays 10 search results per page, set count
         to 10 and offset to 0 to get the first page of results. For each
         subsequent page, increment offset by 10 (for example, 0, 10, 20). it
         is possible for multiple pages to include some overlap in results.
        :type offset: int
        :param promote: A comma-delimited list of answers that you want the
         response to include regardless of their ranking. For example, if you
         set answerCount) to two (2) so Bing returns the top two ranked
         answers, but you also want the response to include news, you'd set
         promote to news. If the top ranked answers are webpages, images,
         videos, and relatedSearches, the response includes webpages and images
         because news is not a ranked answer. But if you set promote to video,
         Bing would promote the video answer into the response and return
         webpages, images, and videos. The answers that you want to promote do
         not count against the answerCount limit. For example, if the ranked
         answers are news, images, and videos, and you set answerCount to 1 and
         promote to news, the response contains news and images. Or, if the
         ranked answers are videos, images, and news, the response contains
         videos and news. Possible values are Computation, Images, News,
         RelatedSearches, SpellSuggestions, TimeZone, Videos, Webpages. Use
         only if you specify answerCount.
        :type promote: list[str or
         ~azure.cognitiveservices.search.websearch.models.AnswerType]
        :param response_filter: A comma-delimited list of answers to include
         in the response. If you do not specify this parameter, the response
         includes all search answers for which there's relevant data. Possible
         filter values are Computation, Images, News, RelatedSearches,
         SpellSuggestions, TimeZone, Videos, Webpages. Although you may use
         this filter to get a single answer, you should instead use the
         answer-specific endpoint in order to get richer results. For example,
         to receive only images, send the request to one of the Image Search
         API endpoints. The RelatedSearches and SpellSuggestions answers do not
         support a separate endpoint like the Image Search API does (only the
         Web Search API returns them). To include answers that would otherwise
         be excluded because of ranking, see the promote query parameter.
        :type response_filter: list[str or
         ~azure.cognitiveservices.search.websearch.models.AnswerType]
        :param safe_search: A filter used to filter adult content. Off: Return
         webpages with adult text, images, or videos. Moderate: Return webpages
         with adult text, but not adult images or videos. Strict: Do not return
         webpages with adult text, images, or videos. The default is Moderate.
         If the request comes from a market that Bing's adult policy requires
         that safeSearch is set to Strict, Bing ignores the safeSearch value
         and uses Strict. If you use the site: query operator, there is the
         chance that the response may contain adult content regardless of what
         the safeSearch query parameter is set to. Use site: only if you are
         aware of the content on the site and your scenario supports the
         possibility of adult content. Possible values include: 'Off',
         'Moderate', 'Strict'
        :type safe_search: str or
         ~azure.cognitiveservices.search.websearch.models.SafeSearch
        :param set_lang: The language to use for user interface strings.
         Specify the language using the ISO 639-1 2-letter language code. For
         example, the language code for English is EN. The default is EN
         (English). Although optional, you should always specify the language.
         Typically, you set setLang to the same language specified by mkt
         unless the user wants the user interface strings displayed in a
         different language. This parameter and the Accept-Language header are
         mutually exclusive; do not specify both. A user interface string is a
         string that's used as a label in a user interface. There are few user
         interface strings in the JSON response objects. Also, any links to
         Bing.com properties in the response objects apply the specified
         language.
        :type set_lang: str
        :param text_decorations: A Boolean value that determines whether
         display strings should contain decoration markers such as hit
         highlighting characters. If true, the strings may include markers. The
         default is false. To specify whether to use Unicode characters or HTML
         tags as the markers, see the textFormat query parameter.
        :type text_decorations: bool
        :param text_format: The type of markers to use for text decorations
         (see the textDecorations query parameter). Possible values are Raw—Use
         Unicode characters to mark content that needs special formatting. The
         Unicode characters are in the range E000 through E019. For example,
         Bing uses E000 and E001 to mark the beginning and end of query terms
         for hit highlighting. HTML—Use HTML tags to mark content that needs
         special formatting. For example, use <b> tags to highlight query terms
         in display strings. The default is Raw. For display strings that
         contain escapable HTML characters such as <, >, and &, if textFormat
         is set to HTML, Bing escapes the characters as appropriate (for
         example, < is escaped to <). Possible values include: 'Raw', 'Html'
        :type text_format: str or
         ~azure.cognitiveservices.search.websearch.models.TextFormat
        :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: SearchResponse or ClientRawResponse if raw=true
        :rtype:
         ~azure.cognitiveservices.search.websearch.models.SearchResponse or
         ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`ErrorResponseException<azure.cognitiveservices.search.websearch.models.ErrorResponseException>`
        """
        # Construct URL
        url = self.search.metadata['url']

        # Construct parameters
        query_parameters = {}
        if answer_count is not None:
            query_parameters['answerCount'] = self._serialize.query("answer_count", answer_count, 'int')
        if country_code is not None:
            query_parameters['cc'] = self._serialize.query("country_code", country_code, 'str')
        if count is not None:
            query_parameters['count'] = self._serialize.query("count", count, 'int')
        if freshness is not None:
            query_parameters['freshness'] = self._serialize.query("freshness", freshness, 'str')
        if market is not None:
            query_parameters['mkt'] = self._serialize.query("market", market, 'str')
        if offset is not None:
            query_parameters['offset'] = self._serialize.query("offset", offset, 'int')
        if promote is not None:
            query_parameters['promote'] = self._serialize.query("promote", promote, '[str]', div=',')
        query_parameters['q'] = self._serialize.query("query", query, 'str')
        if response_filter is not None:
            query_parameters['responseFilter'] = self._serialize.query("response_filter", response_filter, '[str]', div=',')
        if safe_search is not None:
            query_parameters['safeSearch'] = self._serialize.query("safe_search", safe_search, 'str')
        if set_lang is not None:
            query_parameters['setLang'] = self._serialize.query("set_lang", set_lang, 'str')
        if text_decorations is not None:
            query_parameters['textDecorations'] = self._serialize.query("text_decorations", text_decorations, 'bool')
        if text_format is not None:
            query_parameters['textFormat'] = self._serialize.query("text_format", text_format, 'str')

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)
        header_parameters['X-BingApis-SDK'] = self._serialize.header("self.x_bing_apis_sdk", self.x_bing_apis_sdk, 'str')
        if accept_language is not None:
            header_parameters['Accept-Language'] = self._serialize.header("accept_language", accept_language, 'str')
        if pragma is not None:
            header_parameters['Pragma'] = self._serialize.header("pragma", pragma, 'str')
        if user_agent is not None:
            header_parameters['User-Agent'] = self._serialize.header("user_agent", user_agent, 'str')
        if client_id is not None:
            header_parameters['X-MSEdge-ClientID'] = self._serialize.header("client_id", client_id, 'str')
        if client_ip is not None:
            header_parameters['X-MSEdge-ClientIP'] = self._serialize.header("client_ip", client_ip, 'str')
        if location is not None:
            header_parameters['X-Search-Location'] = self._serialize.header("location", location, '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]:
            raise models.ErrorResponseException(self._deserialize, response)

        deserialized = None

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

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

        return deserialized
    search.metadata = {'url': '/search'}