#-------------------------------------------------------------------------
# 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 .constants import (
    DEFAULT_HTTP_TIMEOUT,
    MANAGEMENT_HOST,
)
from .models import (
    Database,
    EventLog,
    FirewallRule,
    Servers,
    ServerQuota,
    ServiceObjective,
)
from .servicemanagementclient import (
    _ServiceManagementClient,
)
from ._common_error import (
    _validate_not_none,
)
from ._serialization import (
    _SqlManagementXmlSerializer,
    _MinidomXmlToObject,
)

class SqlDatabaseManagementService(_ServiceManagementClient):
    ''' Note that this class is a preliminary work on SQL Database
        management. Since it lack a lot a features, final version
        can be slightly different from the current one.
    '''

    def __init__(self, subscription_id=None, cert_file=None,
                 host=MANAGEMENT_HOST, request_session=None,
                 timeout=DEFAULT_HTTP_TIMEOUT):
        '''
        Initializes the sql database management service.

        subscription_id:
            Subscription to manage.
        cert_file:
            Path to .pem certificate file (httplib), or location of the
            certificate in your Personal certificate store (winhttp) in the
            CURRENT_USER\my\CertificateName format.
            If a request_session is specified, then this is unused.
        host:
            Live ServiceClient URL. Defaults to Azure public cloud.
        request_session:
            Session object to use for http requests. If this is specified, it
            replaces the default use of httplib or winhttp. Also, the cert_file
            parameter is unused when a session is passed in.
            The session object handles authentication, and as such can support
            multiple types of authentication: .pem certificate, oauth.
            For example, you can pass in a Session instance from the requests
            library. To use .pem certificate authentication with requests
            library, set the path to the .pem file on the session.cert
            attribute.
        timeout:
            Optional. Timeout for the http request, in seconds.
        '''
        super(SqlDatabaseManagementService, self).__init__(
            subscription_id, cert_file, host, request_session, timeout)
        self.content_type = 'application/xml'

    #--Operations for sql servers ----------------------------------------
    def create_server(self, admin_login, admin_password, location):
        '''
        Create a new Azure SQL Database server.

        admin_login:
            The administrator login name for the new server.
        admin_password:
            The administrator login password for the new server.
        location:
            The region to deploy the new server.
        '''
        _validate_not_none('admin_login', admin_login)
        _validate_not_none('admin_password', admin_password)
        _validate_not_none('location', location)
        response = self.perform_post(
            self._get_servers_path(),
            _SqlManagementXmlSerializer.create_server_to_xml(
                admin_login,
                admin_password,
                location
            )
        )

        return _SqlManagementXmlSerializer.xml_to_create_server_response(
            response.body)

    def set_server_admin_password(self, server_name, admin_password):
        '''
        Reset the administrator password for a server.

        server_name:
            Name of the server to change the password.
        admin_password:
            The new administrator password for the server.
        '''
        _validate_not_none('server_name', server_name)
        _validate_not_none('admin_password', admin_password)
        return self._perform_post(
            self._get_servers_path(server_name) + '?op=ResetPassword',
            _SqlManagementXmlSerializer.set_server_admin_password_to_xml(
                admin_password
            )
        )

    def delete_server(self, server_name):
        '''
        Deletes an Azure SQL Database server (including all its databases).

        server_name:
            Name of the server you want to delete.
        '''
        _validate_not_none('server_name', server_name)
        return self._perform_delete(
            self._get_servers_path(server_name))

    def list_servers(self):
        '''
        List the SQL servers defined on the account.
        '''
        return self._perform_get(self._get_servers_path(),
                                 Servers)

    def list_quotas(self, server_name):
        '''
        Gets quotas for an Azure SQL Database Server.

        server_name:
            Name of the server.
        '''
        _validate_not_none('server_name', server_name)
        response = self._perform_get(self._get_quotas_path(server_name),
                                     None)
        return _MinidomXmlToObject.parse_service_resources_response(
            response, ServerQuota)

    def get_server_event_logs(self, server_name, start_date,
                              interval_size_in_minutes, event_types=''):
        '''
        Gets the event logs for an Azure SQL Database Server.

        server_name:
            Name of the server to retrieve the event logs from.
        start_date:
            The starting date and time of the events to retrieve in UTC format,
            for example '2011-09-28 16:05:00'.
        interval_size_in_minutes:
            Size of the event logs to retrieve (in minutes).
            Valid values are: 5, 60, or 1440.
        event_types:
            The event type of the log entries you want to retrieve.
            Valid values are:
                - connection_successful
                - connection_failed
                - connection_terminated
                - deadlock
                - throttling
                - throttling_long_transaction
            To return all event types pass in an empty string.
        '''
        _validate_not_none('server_name', server_name)
        _validate_not_none('start_date', start_date)
        _validate_not_none('interval_size_in_minutes', interval_size_in_minutes)
        _validate_not_none('event_types', event_types)
        path = self._get_server_event_logs_path(server_name) + \
               '?startDate={0}&intervalSizeInMinutes={1}&eventTypes={2}'.format(
            start_date, interval_size_in_minutes, event_types)
        response = self._perform_get(path, None)
        return _MinidomXmlToObject.parse_service_resources_response(
            response, EventLog)

    #--Operations for firewall rules ------------------------------------------
    def create_firewall_rule(self, server_name, name, start_ip_address,
                             end_ip_address):
        '''
        Creates an Azure SQL Database server firewall rule.

        server_name:
            Name of the server to set the firewall rule on.
        name:
            The name of the new firewall rule.
        start_ip_address:
            The lowest IP address in the range of the server-level firewall
            setting. IP addresses equal to or greater than this can attempt to
            connect to the server. The lowest possible IP address is 0.0.0.0.
        end_ip_address:
            The highest IP address in the range of the server-level firewall
            setting. IP addresses equal to or less than this can attempt to
            connect to the server. The highest possible IP address is
            255.255.255.255.
        '''
        _validate_not_none('server_name', server_name)
        _validate_not_none('name', name)
        _validate_not_none('start_ip_address', start_ip_address)
        _validate_not_none('end_ip_address', end_ip_address)
        return self._perform_post(
            self._get_firewall_rules_path(server_name),
            _SqlManagementXmlSerializer.create_firewall_rule_to_xml(
                name, start_ip_address, end_ip_address
            )
        )

    def update_firewall_rule(self, server_name, name, start_ip_address,
                             end_ip_address):
        '''
        Update a firewall rule for an Azure SQL Database server.

        server_name:
            Name of the server to set the firewall rule on.
        name:
            The name of the firewall rule to update.
        start_ip_address:
            The lowest IP address in the range of the server-level firewall
            setting. IP addresses equal to or greater than this can attempt to
            connect to the server. The lowest possible IP address is 0.0.0.0.
        end_ip_address:
            The highest IP address in the range of the server-level firewall
            setting. IP addresses equal to or less than this can attempt to
            connect to the server. The highest possible IP address is
            255.255.255.255.
        '''
        _validate_not_none('server_name', server_name)
        _validate_not_none('name', name)
        _validate_not_none('start_ip_address', start_ip_address)
        _validate_not_none('end_ip_address', end_ip_address)
        return self._perform_put(
            self._get_firewall_rules_path(server_name, name),
            _SqlManagementXmlSerializer.update_firewall_rule_to_xml(
                name, start_ip_address, end_ip_address
            )
        )

    def delete_firewall_rule(self, server_name, name):
        '''
        Deletes an Azure SQL Database server firewall rule.

        server_name:
            Name of the server with the firewall rule you want to delete.
        name:
            Name of the firewall rule you want to delete.
        '''
        _validate_not_none('server_name', server_name)
        _validate_not_none('name', name)
        return self._perform_delete(
            self._get_firewall_rules_path(server_name, name))

    def list_firewall_rules(self, server_name):
        '''
        Retrieves the set of firewall rules for an Azure SQL Database Server.

        server_name:
            Name of the server.
        '''
        _validate_not_none('server_name', server_name)
        response = self._perform_get(self._get_firewall_rules_path(server_name),
                                     None)
        return _MinidomXmlToObject.parse_service_resources_response(
            response, FirewallRule)

    def list_service_level_objectives(self, server_name):
        '''
        Gets the service level objectives for an Azure SQL Database server.

        server_name:
            Name of the server.
        '''
        _validate_not_none('server_name', server_name)
        response = self._perform_get(
            self._get_service_objectives_path(server_name), None)
        return _MinidomXmlToObject.parse_service_resources_response(
            response, ServiceObjective)

    #--Operations for sql databases ----------------------------------------
    def create_database(self, server_name, name, service_objective_id,
                        edition=None, collation_name=None,
                        max_size_bytes=None):
        '''
        Creates a new Azure SQL Database.

        server_name:
            Name of the server to contain the new database.
        name:
            Required. The name for the new database. See Naming Requirements
            in Azure SQL Database General Guidelines and Limitations and
            Database Identifiers for more information.
        service_objective_id:
            Required. The GUID corresponding to the performance level for
            Edition. See List Service Level Objectives for current values.
        edition:
            Optional. The Service Tier (Edition) for the new database. If
            omitted, the default is Web. Valid values are Web, Business,
            Basic, Standard, and Premium. See Azure SQL Database Service Tiers
            (Editions) and Web and Business Edition Sunset FAQ for more
            information.
        collation_name:
            Optional. The database collation. This can be any collation
            supported by SQL. If omitted, the default collation is used. See
            SQL Server Collation Support in Azure SQL Database General
            Guidelines and Limitations for more information.
        max_size_bytes:
            Optional. Sets the maximum size, in bytes, for the database. This
            value must be within the range of allowed values for Edition. If
            omitted, the default value for the edition is used. See Azure SQL
            Database Service Tiers (Editions) for current maximum databases
            sizes. Convert MB or GB values to bytes.
            1 MB = 1048576 bytes. 1 GB = 1073741824 bytes.
        '''
        _validate_not_none('server_name', server_name)
        _validate_not_none('name', name)
        _validate_not_none('service_objective_id', service_objective_id)
        return self._perform_post(
            self._get_databases_path(server_name),
            _SqlManagementXmlSerializer.create_database_to_xml(
                name, service_objective_id, edition, collation_name,
                max_size_bytes
            )
        )

    def update_database(self, server_name, name, new_database_name=None,
                        service_objective_id=None, edition=None,
                        max_size_bytes=None):
        '''
        Updates existing database details.

        server_name:
            Name of the server to contain the new database.
        name:
            Required. The name for the new database. See Naming Requirements
            in Azure SQL Database General Guidelines and Limitations and
            Database Identifiers for more information.
        new_database_name:
            Optional. The new name for the new database.
        service_objective_id:
            Optional. The new service level to apply to the database. For more
            information about service levels, see Azure SQL Database Service
            Tiers and Performance Levels. Use List Service Level Objectives to
            get the correct ID for the desired service objective.
        edition:
            Optional. The new edition for the new database.
        max_size_bytes:
            Optional. The new size of the database in bytes. For information on
            available sizes for each edition, see Azure SQL Database Service
            Tiers (Editions).
        '''
        _validate_not_none('server_name', server_name)
        _validate_not_none('name', name)
        return self._perform_put(
            self._get_databases_path(server_name, name),
            _SqlManagementXmlSerializer.update_database_to_xml(
                new_database_name, service_objective_id, edition,
                max_size_bytes
            )
        )

    def delete_database(self, server_name, name):
        '''
        Deletes an Azure SQL Database.

        server_name:
            Name of the server where the database is located.
        name:
            Name of the database to delete.
        '''
        return self._perform_delete(self._get_databases_path(server_name, name))

    def list_databases(self, name):
        '''
        List the SQL databases defined on the specified server name
        '''
        response = self._perform_get(self._get_list_databases_path(name),
                                     None)
        return _MinidomXmlToObject.parse_service_resources_response(
            response, Database)

    #--Helper functions --------------------------------------------------
    def _get_servers_path(self, server_name=None):
        return self._get_path('services/sqlservers/servers', server_name)

    def _get_firewall_rules_path(self, server_name, name=None):
        path = self._get_servers_path(server_name) + '/firewallrules'
        if name:
            path = path + '/' + name
        return path

    def _get_databases_path(self, server_name, name=None):
        path = self._get_servers_path(server_name) + '/databases'
        if name:
            path = path + '/' + name
        return path

    def _get_server_event_logs_path(self, server_name):
        return self._get_servers_path(server_name) + '/events'

    def _get_service_objectives_path(self, server_name):
        return self._get_servers_path(server_name) + '/serviceobjectives'

    def _get_quotas_path(self, server_name, name=None):
        path = self._get_servers_path(server_name) + '/serverquotas'
        if name:
            path = path + '/' + name
        return path

    def _get_list_databases_path(self, name):
        # *contentview=generic is mandatory*
        return self._get_path('services/sqlservers/servers/',
                              name) + '/databases?contentview=generic'


# 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 ImagesOperations(object):
    """ImagesOperations 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 visual_search(
            self, accept_language=None, content_type=None, user_agent=None, client_id=None, client_ip=None, location=None, market=None, safe_search=None, set_lang=None, knowledge_request=None, image=None, custom_headers=None, raw=False, **operation_config):
        """Visual Search API lets you discover insights about an image such as
        visually similar images, shopping sources, and related searches. The
        API can also perform text recognition, identify entities (people,
        places, things), return other topical content for the user to explore,
        and more. For more information, see [Visual Search
        Overview](https://docs.microsoft.com/azure/cognitive-services/bing-visual-search/overview).

        :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](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-visual-search-api-v7-reference#setlang)
         query parameter are mutually exclusive; do not specify both. If you
         set this header, you must also specify the
         [cc](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-visual-search-api-v7-reference#cc)
         query parameter. To determine the market to return results for, Bing
         uses the first supported language it finds from the list and combines
         it with the cc parameter value. If the list does not include a
         supported language, Bing finds the closest language and market that
         supports the request or it uses an aggregated or default market for
         the results. To determine the market that Bing used, see the
         BingAPIs-Market header. Use this header and the cc query parameter
         only if you specify multiple languages. Otherwise, use the
         [mkt](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-visual-search-api-v7-reference#mkt)
         and
         [setLang](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-visual-search-api-v7-reference#setlang)
         query parameters. 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. Any links to Bing.com properties in the
         response objects apply the specified language.
        :type accept_language: str
        :param content_type: Must be set to multipart/form-data and include a
         boundary parameter (for example, multipart/form-data;
         boundary=<boundary string>). For more details, see [Content form
         types](
         https://docs.microsoft.com/en-us/azure/cognitive-services/bing-visual-search/overview#content-form-types).
        :type content_type: 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 encouraged to always specify this header.
         The user-agent should be the same string that any commonly used
         browser sends. For information about user agents, see [RFC
         2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html). The
         following are examples of user-agent strings. Windows Phone:
         Mozilla/5.0 (compatible; MSIE 10.0; Windows Phone 8.0; Trident/6.0;
         IEMobile/10.0; ARM; Touch; NOKIA; Lumia 822). Android: Mozilla / 5.0
         (Linux; U; Android 2.3.5; en - us; SCH - I500 Build / GINGERBREAD)
         AppleWebKit / 533.1 (KHTML; like Gecko) Version / 4.0 Mobile Safari /
         533.1. iPhone: Mozilla / 5.0 (iPhone; CPU iPhone OS 6_1 like Mac OS X)
         AppleWebKit / 536.26 (KHTML; like Gecko) Mobile / 10B142 iPhone4; 1
         BingWeb / 3.03.1428.20120423. PC: Mozilla / 5.0 (Windows NT 6.3;
         WOW64; Trident / 7.0; Touch; rv:11.0) like Gecko. iPad: Mozilla / 5.0
         (iPad; CPU OS 7_0 like Mac OS X) AppleWebKit / 537.51.1 (KHTML, like
         Gecko) Version / 7.0 Mobile / 11A465 Safari / 9537.53.
        :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. ATTENTION: You must ensure that
         this Client ID is not linkable to any authenticatable user account
         information. 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 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. For a list of possible market values, see [Market
         Codes](https://docs.microsoft.com/en-us/azure/cognitive-services/bing-visual-search/supported-countries-markets).
         NOTE: 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](https://docs.microsoft.com/en-us/azure/cognitive-services/bing-visual-search/supported-countries-markets),
         Bing uses a best fit market code based on an internal mapping that is
         subject to change.
        :type market: str
        :param safe_search: Filter the image results in actions with type
         'VisualSearch' for adult content. The following are the possible
         filter values. Off: May return images with adult content. Moderate: Do
         not return images with adult content. Strict: Do not return images
         with adult content. 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: filter in the knowledge request, 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.visualsearch.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. 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 knowledge_request: The form data is a JSON object that
         identifies the image using an insights token or URL to the image. The
         object may also include an optional crop area that identifies an area
         of interest in the image. The insights token and URL are mutually
         exclusive – do not specify both. You may specify knowledgeRequest form
         data and image form data in the same request only if knowledgeRequest
         form data specifies the cropArea field only (it must not include an
         insights token or URL).
        :type knowledge_request: str
        :param image: The form data is an image binary. The
         Content-Disposition header's name parameter must be set to "image".
         You must specify an image binary if you do not use knowledgeRequest
         form data to specify the image; you may not use both forms to specify
         an image. You may specify knowledgeRequest form data and image form
         data in the same request only if knowledgeRequest form data specifies
         the cropArea field only  (it must not include an insights token or
         URL).
        :type image: Generator
        :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: ImageKnowledge or ClientRawResponse if raw=true
        :rtype:
         ~azure.cognitiveservices.search.visualsearch.models.ImageKnowledge or
         ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`ErrorResponseException<azure.cognitiveservices.search.visualsearch.models.ErrorResponseException>`
        """
        # Construct URL
        url = self.visual_search.metadata['url']
        path_format_arguments = {
            'Endpoint': self._serialize.url("self.config.endpoint", self.config.endpoint, 'str', skip_quote=True)
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}
        if market is not None:
            query_parameters['mkt'] = self._serialize.query("market", market, 'str')
        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')

        # Construct headers
        header_parameters = {}
        header_parameters['Accept'] = 'application/json'
        header_parameters['Content-Type'] = 'multipart/form-data'
        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 content_type is not None:
            header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, '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 form data
        form_data_content = {
            'knowledgeRequest': knowledge_request,
            'image': image,
        }

        # Construct and send request
        request = self._client.post(url, query_parameters, header_parameters, form_content=form_data_content)
        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('ImageKnowledge', response)

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

        return deserialized
    visual_search.metadata = {'url': '/images/visualsearch'}


# 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 TopLevelDomainsOperations(object):
    """TopLevelDomainsOperations 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-02-01".
    """

    models = models

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

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

        self.config = config

    def list(
            self, custom_headers=None, raw=False, **operation_config):
        """Get all top-level domains supported for registration.

        Get all top-level domains supported for registration.

        :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 TopLevelDomain
        :rtype:
         ~azure.mgmt.web.models.TopLevelDomainPaged[~azure.mgmt.web.models.TopLevelDomain]
        :raises:
         :class:`DefaultErrorResponseException<azure.mgmt.web.models.DefaultErrorResponseException>`
        """
        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['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.DefaultErrorResponseException(self._deserialize, response)

            return response

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

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

        return deserialized
    list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.DomainRegistration/topLevelDomains'}

    def get(
            self, name, custom_headers=None, raw=False, **operation_config):
        """Get details of a top-level domain.

        Get details of a top-level domain.

        :param name: Name of the top-level domain.
        :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: TopLevelDomain or ClientRawResponse if raw=true
        :rtype: ~azure.mgmt.web.models.TopLevelDomain or
         ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`DefaultErrorResponseException<azure.mgmt.web.models.DefaultErrorResponseException>`
        """
        # Construct URL
        url = self.get.metadata['url']
        path_format_arguments = {
            'name': self._serialize.url("name", 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]:
            raise models.DefaultErrorResponseException(self._deserialize, response)

        deserialized = None

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

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

        return deserialized
    get.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.DomainRegistration/topLevelDomains/{name}'}

    def list_agreements(
            self, name, include_privacy=None, for_transfer=None, custom_headers=None, raw=False, **operation_config):
        """Gets all legal agreements that user needs to accept before purchasing a
        domain.

        Gets all legal agreements that user needs to accept before purchasing a
        domain.

        :param name: Name of the top-level domain.
        :type name: str
        :param include_privacy: If true, then the list of
         agreements will include agreements for domain privacy as well;
         otherwise, false.
        :type include_privacy: bool
        :param for_transfer: If true, then the list of agreements
         will include agreements for domain transfer as well; otherwise,
         false.
        :type for_transfer: bool
        :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 TldLegalAgreement
        :rtype:
         ~azure.mgmt.web.models.TldLegalAgreementPaged[~azure.mgmt.web.models.TldLegalAgreement]
        :raises:
         :class:`DefaultErrorResponseException<azure.mgmt.web.models.DefaultErrorResponseException>`
        """
        agreement_option = models.TopLevelDomainAgreementOption(include_privacy=include_privacy, for_transfer=for_transfer)

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

            if not next_link:
                # Construct URL
                url = self.list_agreements.metadata['url']
                path_format_arguments = {
                    'name': self._serialize.url("name", 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'
            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(agreement_option, 'TopLevelDomainAgreementOption')

            # 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]:
                raise models.DefaultErrorResponseException(self._deserialize, response)

            return response

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

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

        return deserialized
    list_agreements.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.DomainRegistration/topLevelDomains/{name}/listAgreements'}


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

import asyncio
import logging
from urllib.parse import urlparse

from uamqp import AMQPClientAsync
from uamqp.message import Message, MessageProperties
from uamqp import authentication
from uamqp import constants, errors

from azure.servicebus.common.utils import create_properties, get_running_loop
from azure.servicebus.common.errors import (
    _ServiceBusErrorPolicy,
    ServiceBusError,
    ServiceBusConnectionError,
    InvalidHandlerState,
    ServiceBusAuthorizationError)

_log = logging.getLogger(__name__)

class BaseHandler:  # pylint: disable=too-many-instance-attributes

    def __init__(self, endpoint, auth_config, *, loop=None, connection=None, encoding='UTF-8', debug=False, **kwargs):
        self.loop = loop or get_running_loop()
        self.running = False
        self.error = None
        self.endpoint = endpoint
        self.entity = urlparse(endpoint).path.strip('/')
        self.mgmt_target = self.entity + "/$management"
        self.debug = debug
        self.encoding = encoding
        self.auth_config = auth_config
        self.connection = connection
        self.auto_reconnect = kwargs.pop('auto_reconnect', True)
        self.properties = create_properties()
        self.error_policy = kwargs.pop('error_policy', None)
        self.handler_kwargs = kwargs
        if not self.error_policy:
            max_retries = kwargs.pop('max_message_retries', 3)
            is_session = hasattr(self, 'session_id')
            self.error_policy = _ServiceBusErrorPolicy(max_retries=max_retries, is_session=is_session)
        self._handler = None
        self._build_handler()

    async def __aenter__(self):
        """Open the handler in a context manager."""
        await self.open()
        return self

    async def __aexit__(self, *args):
        """Close the handler when exiting a context manager."""
        await self.close()

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

    async def _mgmt_request_response(self, operation, message, callback, **kwargs):
        if not self.running:
            raise InvalidHandlerState("Client connection is closed.")

        mgmt_msg = Message(
            body=message,
            properties=MessageProperties(
                reply_to=self.mgmt_target,
                encoding=self.encoding,
                **kwargs))
        try:
            return await self._handler.mgmt_request_async(
                mgmt_msg,
                operation,
                op_type=b"entity-mgmt",
                node=self.mgmt_target.encode(self.encoding),
                timeout=5000,
                callback=callback)
        except Exception as exp:  # pylint: disable=broad-except
            raise ServiceBusError("Management request failed: {}".format(exp), exp)

    async def _handle_exception(self, exception):
        if isinstance(exception, (errors.LinkDetach, errors.ConnectionClose)):
            if exception.action and exception.action.retry and self.auto_reconnect:
                _log.info("Async handler detached. Attempting reconnect.")
                await self.reconnect()
            elif exception.condition == constants.ErrorCodes.UnauthorizedAccess:
                _log.info("Async handler detached. Shutting down.")
                error = ServiceBusAuthorizationError(str(exception), exception)
                await self.close(exception=error)
                raise error
            else:
                _log.info("Async handler detached. Shutting down.")
                error = ServiceBusConnectionError(str(exception), exception)
                await self.close(exception=error)
                raise error
        elif isinstance(exception, errors.MessageHandlerError):
            if self.auto_reconnect:
                _log.info("Async handler error. Attempting reconnect.")
                await self.reconnect()
            else:
                _log.info("Async handler error. Shutting down.")
                error = ServiceBusConnectionError(str(exception), exception)
                await self.close(exception=error)
                raise error
        elif isinstance(exception, errors.AMQPConnectionError):
            message = "Failed to open handler: {}".format(exception)
            raise ServiceBusConnectionError(message, exception)
        else:
            _log.info("Unexpected error occurred (%r). Shutting down.", exception)
            error = ServiceBusError("Handler failed: {}".format(exception), exception)
            await self.close(exception=error)
            raise error

    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.
        """
        await self._handler.close()
        self._build_handler()
        await self.open()

    async def open(self):
        """Open handler connection and authenticate session.

        If the handler is already open, this operation will do nothing.
        A handler opened with this method must be explicitly closed.
        It is recommended to open a handler within a context manager as
        opposed to calling the method directly.

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

        Example:
            .. literalinclude:: ../examples/async_examples/test_examples_async.py
                :start-after: [START open_close_sender_directly]
                :end-before: [END open_close_sender_directly]
                :language: python
                :dedent: 4
                :caption: Explicitly open and close a Sender.

        """
        if self.running:
            return
        self.running = True
        try:
            await self._handler.open_async(connection=self.connection)
            while not await self._handler.client_ready_async():
                await asyncio.sleep(0.05)
        except Exception as e:  # pylint: disable=broad-except
            try:
                await self._handle_exception(e)
            except:
                self.running = False
                raise

    async def close(self, exception=None):
        """Close down the handler connection.

        If the handler has already closed,
        this operation will do nothing. An optional exception can be passed in to
        indicate that the handler was shutdown due to error.
        It is recommended to open a handler within a context manager as
        opposed to calling the method directly.

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

        :param exception: An optional exception if the handler is closing
         due to an error.
        :type exception: Exception

        Example:
            .. literalinclude:: ../examples/async_examples/test_examples_async.py
                :start-after: [START open_close_sender_directly]
                :end-before: [END open_close_sender_directly]
                :language: python
                :dedent: 4
                :caption: Explicitly open and close a Sender.

        """
        self.running = False
        if self.error:
            return
        if isinstance(exception, ServiceBusError):
            self.error = exception
        elif exception:
            self.error = ServiceBusError(str(exception))
        else:
            self.error = ServiceBusError("This message handler is now closed.")
        await self._handler.close_async()


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

import asyncio
import datetime
import functools
import uuid
import collections

import six

from uamqp import ReceiveClientAsync
from uamqp import authentication
from uamqp import constants, types, errors

from azure.servicebus.aio import Message, DeferredMessage
from azure.servicebus.aio.async_base_handler import BaseHandler
from azure.servicebus.common import mgmt_handlers, mixins
from azure.servicebus.common.errors import (
    InvalidHandlerState,
    NoActiveSession,
    SessionLockExpired)
from azure.servicebus.common.constants import (
    SESSION_LOCK_LOST,
    SESSION_LOCK_TIMEOUT,
    REQUEST_RESPONSE_RENEWLOCK_OPERATION,
    REQUEST_RESPONSE_GET_SESSION_STATE_OPERATION,
    REQUEST_RESPONSE_SET_SESSION_STATE_OPERATION,
    REQUEST_RESPONSE_RENEW_SESSION_LOCK_OPERATION,
    REQUEST_RESPONSE_PEEK_OPERATION,
    REQUEST_RESPONSE_GET_MESSAGE_SESSIONS_OPERATION,
    REQUEST_RESPONSE_RECEIVE_BY_SEQUENCE_NUMBER,
    REQUEST_RESPONSE_UPDATE_DISPOSTION_OPERATION,
    ReceiveSettleMode)

class Receiver(collections.abc.AsyncIterator, BaseHandler):  # pylint: disable=too-many-instance-attributes
    """A message receiver.

    This receive handler acts as an iterable message stream for retrieving
    messages for a Service Bus entity. It operates a single connection that must be opened and
    closed on completion. The service connection will remain open for the entirety of the iterator.
    If you find yourself only partially iterating the message stream, you should run the receiver
    in a `with` statement to ensure the connection is closed.
    The Receiver should not be instantiated directly, and should be accessed from a `QueueClient` or
    `SubscriptionClient` using the `get_receiver()` method.

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

    :param handler_id: The ID used as the connection name for the Receiver.
    :type handler_id: str
    :param source: The endpoint from which to receive messages.
    :type source: ~uamqp.Source
    :param auth_config: The SASL auth credentials.
    :type auth_config: dict[str, str]
    :param loop: An async event loop
    :type loop: ~asyncio.EventLoop
    :param connection: A shared connection [not yet supported].
    :type connection: ~uamqp.Connection
    :param mode: The receive connection mode. Value must be either PeekLock or ReceiveAndDelete.
    :type mode: ~azure.servicebus.common.constants.ReceiveSettleMode
    :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

    Example:
        .. literalinclude:: ../examples/async_examples/test_examples_async.py
            :start-after: [START open_close_receiver_context]
            :end-before: [END open_close_receiver_context]
            :language: python
            :dedent: 4
            :caption: Running a queue receiver within a context manager.

    """

    def __init__(
            self, handler_id, source, auth_config, *, loop=None, connection=None,
            mode=ReceiveSettleMode.PeekLock, encoding='UTF-8', debug=False, **kwargs):
        self._used = asyncio.Event()
        self.name = "SBReceiver-{}".format(handler_id)
        self.last_received = None
        self.mode = mode
        self.message_iter = None
        super(Receiver, self).__init__(
            source, auth_config, loop=loop, connection=connection, encoding=encoding, debug=debug, **kwargs)

    async def __anext__(self):
        await self._can_run()
        while True:
            if self.receiver_shutdown:
                await self.close()
                raise StopAsyncIteration
            try:
                received = await self.message_iter.__anext__()
                wrapped = self._build_message(received)
                return wrapped
            except StopAsyncIteration:
                await self.close()
                raise
            except Exception as e:  # pylint: disable=broad-except
                await self._handle_exception(e)

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

    async def _build_receiver(self):
        """This is a temporary patch pending a fix in uAMQP."""
        # pylint: disable=protected-access
        self._handler.message_handler = self._handler.receiver_type(
            self._handler._session,
            self._handler._remote_address,
            self._handler._name,
            on_message_received=self._handler._message_received,
            name='receiver-link-{}'.format(uuid.uuid4()),
            debug=self._handler._debug_trace,
            prefetch=self._handler._prefetch,
            max_message_size=self._handler._max_message_size,
            properties=self._handler._link_properties,
            error_policy=self._handler._error_policy,
            encoding=self._handler._encoding,
            loop=self._handler.loop)
        if self.mode != ReceiveSettleMode.PeekLock:
            self._handler.message_handler.send_settle_mode = constants.SenderSettleMode.Settled
            self._handler.message_handler.receive_settle_mode = constants.ReceiverSettleMode.ReceiveAndDelete
            self._handler.message_handler._settle_mode = constants.ReceiverSettleMode.ReceiveAndDelete
        await self._handler.message_handler.open_async()

    def _build_message(self, received):
        message = Message(None, message=received)
        message._receiver = self  # pylint: disable=protected-access
        self.last_received = message.sequence_number
        return message

    async def _can_run(self):
        if self._used.is_set():
            raise InvalidHandlerState("Receiver has already closed.")
        if self.receiver_shutdown:
            await self.close()
            raise InvalidHandlerState("Receiver has already closed.")
        if not self.running:
            await self.open()

    async def _renew_locks(self, *lock_tokens):
        message = {'lock-tokens': types.AMQPArray(lock_tokens)}
        return await self._mgmt_request_response(
            REQUEST_RESPONSE_RENEWLOCK_OPERATION,
            message,
            mgmt_handlers.lock_renew_op)

    async def _settle_deferred(self, settlement, lock_tokens, dead_letter_details=None):
        message = {
            'disposition-status': settlement,
            'lock-tokens': types.AMQPArray(lock_tokens)}
        if dead_letter_details:
            message.update(dead_letter_details)
        return await self._mgmt_request_response(
            REQUEST_RESPONSE_UPDATE_DISPOSTION_OPERATION,
            message,
            mgmt_handlers.default)

    @property
    def receiver_shutdown(self):
        """Whether the receiver connection has been marked for shutdown.

        If this value is `True` - it does not indicate that the connection
        has yet been closed.
        This property is used internally and should not be relied upon to asses
        the status of the connection.

        :rtype: bool
        """
        if self._handler:
            return self._handler._shutdown  # pylint: disable=protected-access
        return True

    @receiver_shutdown.setter
    def receiver_shutdown(self, value):
        """Mark the connection as ready for shutdown.

        This property is used internally and should not be set in normal usage.

        :param bool value: Whether to shutdown the connection.
        """
        if self._handler:
            self._handler._shutdown = value  # pylint: disable=protected-access
        else:
            raise ValueError("Receiver has no AMQP handler")

    @property
    def queue_size(self):
        """The current size of the unprocessed message queue.

        :rtype: int
        """
        # pylint: disable=protected-access
        if self._handler._received_messages:
            return self._handler._received_messages.qsize()
        return 0

    async def open(self):
        """Open receiver connection and authenticate session.

        If the receiver is already open, this operation will do nothing.
        This method will be called automatically when one starts to iterate
        messages in the receiver, so there should be no need to call it directly.
        A receiver opened with this method must be explicitly closed.
        It is recommended to open a handler within a context manager as
        opposed to calling the method directly.

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

        """
        if self.running:
            return
        self.running = True
        try:
            await self._handler.open_async(connection=self.connection)
            self.message_iter = self._handler.receive_messages_iter_async()
            while not await self._handler.auth_complete_async():
                await asyncio.sleep(0.05)
            await self._build_receiver()
            while not await self._handler.client_ready_async():
                await asyncio.sleep(0.05)
        except Exception as e:  # pylint: disable=broad-except
            try:
                await self._handle_exception(e)
            except:
                self.running = False
                raise

    async def close(self, exception=None):
        """Close down the receiver connection.

        If the receiver has already closed, this operation will do nothing. An optional
        exception can be passed in to indicate that the handler was shutdown due to error.
        It is recommended to open a handler within a context manager as
        opposed to calling the method directly.
        The receiver will be implicitly closed on completion of the message iterator,
        however this method will need to be called explicitly if the message iterator is not run
        to completion.

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

        :param exception: An optional exception if the handler is closing
         due to an error.
        :type exception: Exception

        Example:
            .. literalinclude:: ../examples/async_examples/test_examples_async.py
                :start-after: [START open_close_receiver_directly]
                :end-before: [END open_close_receiver_directly]
                :language: python
                :dedent: 4
                :caption: Iterate then explicitly close a Receiver.

        """
        if not self.running:
            return
        self.running = False
        self.receiver_shutdown = True
        self._used.set()
        await super(Receiver, self).close(exception=exception)

    async def peek(self, count=1, start_from=0):
        """Browse messages currently pending in the queue.

        Peeked messages are not removed from queue, nor are they locked. They cannot be completed,
        deferred or dead-lettered.

        :param count: The maximum number of messages to try and peek. The default
         value is 1.
        :type count: int
        :param start_from: A message sequence number from which to start browsing messages.
        :type start_from: int
        :rtype: list[~azure.servicebus.common.message.PeekMessage]

        Example:
            .. literalinclude:: ../examples/async_examples/test_examples_async.py
                :start-after: [START receiver_peek_messages]
                :end-before: [END receiver_peek_messages]
                :language: python
                :dedent: 4
                :caption: Peek messages in the queue.

        """
        await self._can_run()
        if not start_from:
            start_from = self.last_received or 1
        if int(count) < 1:
            raise ValueError("count must be 1 or greater.")
        if int(start_from) < 1:
            raise ValueError("start_from must be 1 or greater.")

        message = {
            'from-sequence-number': types.AMQPLong(start_from),
            'message-count': count
        }
        return await self._mgmt_request_response(
            REQUEST_RESPONSE_PEEK_OPERATION,
            message,
            mgmt_handlers.peek_op)

    async def receive_deferred_messages(self, sequence_numbers, mode=ReceiveSettleMode.PeekLock):
        """Receive messages that have previously been deferred.

        When receiving deferred messages from a partitioned entity, all of the supplied
        sequence numbers must be messages from the same partition.

        :param sequence_numbers: A list of the sequence numbers of messages that have been
         deferred.
        :type sequence_numbers: list[int]
        :param mode: The receive mode, default value is PeekLock.
        :type mode: ~azure.servicebus.common.constants.ReceiveSettleMode
        :rtype: list[~azure.servicebus.aio.async_message.DeferredMessage]

        Example:
            .. literalinclude:: ../examples/async_examples/test_examples_async.py
                :start-after: [START receiver_defer_messages]
                :end-before: [END receiver_defer_messages]
                :language: python
                :dedent: 8
                :caption: Defer messages, then retrieve them by sequence number.

        """
        if not sequence_numbers:
            raise ValueError("At least one sequence number must be specified.")
        await self._can_run()
        try:
            receive_mode = mode.value.value
        except AttributeError:
            receive_mode = int(mode)
        message = {
            'sequence-numbers': types.AMQPArray([types.AMQPLong(s) for s in sequence_numbers]),
            'receiver-settle-mode': types.AMQPuInt(receive_mode)
        }
        handler = functools.partial(mgmt_handlers.deferred_message_op, mode=receive_mode, message_type=DeferredMessage)
        messages = await self._mgmt_request_response(
            REQUEST_RESPONSE_RECEIVE_BY_SEQUENCE_NUMBER,
            message,
            handler)
        for m in messages:
            m._receiver = self  # pylint: disable=protected-access
        return messages

    async def fetch_next(self, max_batch_size=None, timeout=None):
        """Receive a batch of messages at once.

        This approach it optimal if you wish to process multiple messages simultaneously.
        Note that the number of messages retrieved in a single batch will be dependent on
        whether `prefetch` was set for the receiver. This call will prioritize returning
        quickly over meeting a specified batch size, and so will return as soon as at least
        one message is received and there is a gap in incoming messages regardless
        of the specified batch size.

        :param max_batch_size: Maximum number of messages in the batch. Actual number
         returned will depend on prefetch size and incoming stream rate.
        :type max_batch_size: int
        :param timeout: The time to wait in seconds for the first message to arrive.
         If no messages arrive, and no timeout is specified, this call will not return
         until the connection is closed. If specified, an no messages arrive within the
         timeout period, an empty list will be returned.
        :rtype: list[~azure.servicebus.aio.async_message.Message]

        Example:
            .. literalinclude:: ../examples/async_examples/test_examples_async.py
                :start-after: [START receiver_fetch_batch]
                :end-before: [END receiver_fetch_batch]
                :language: python
                :dedent: 4
                :caption: Fetch a batch of messages.

        """
        await self._can_run()
        wrapped_batch = []
        max_batch_size = max_batch_size or self._handler._prefetch  # pylint: disable=protected-access
        try:
            timeout_ms = 1000 * timeout if timeout else 0
            batch = await self._handler.receive_message_batch_async(
                max_batch_size=max_batch_size,
                timeout=timeout_ms)
            for received in batch:
                message = self._build_message(received)
                wrapped_batch.append(message)
        except Exception as e:  # pylint: disable=broad-except
            await self._handle_exception(e)
        return wrapped_batch

class SessionReceiver(Receiver, mixins.SessionMixin):
    """A session message receiver.

    This receive handler acts as an iterable message stream for retrieving
    messages for a sessionful Service Bus entity. It operates a single connection that must be opened and
    closed on completion. The service connection will remain open for the entirety of the iterator.
    If you find yourself only partially iterating the message stream, you should run the receiver
    in a `with` statement to ensure the connection is closed.
    The Receiver should not be instantiated directly, and should be accessed from a `QueueClient` or
    `SubscriptionClient` using the `get_receiver()` method.
    When receiving messages from a session, connection errors that would normally be automatically
    retried will instead raise an error due to the loss of the lock on a particular session.
    A specific session can be specified, or the receiver can retrieve any available session using
    the `NEXT_AVAILABLE` constant.

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

    :param handler_id: The ID used as the connection name for the Receiver.
    :type handler_id: str
    :param source: The endpoint from which to receive messages.
    :type source: ~uamqp.Source
    :param auth_config: The SASL auth credentials.
    :type auth_config: dict[str, str]
    :param session: The ID of the session to receive from.
    :type session: str or ~azure.servicebus.common.constants.NEXT_AVAILABLE
    :param loop: An async event loop
    :type loop: ~asyncio.EventLoop
    :param connection: A shared connection [not yet supported].
    :type connection: ~uamqp.Connection
    :param mode: The receive connection mode. Value must be either PeekLock or ReceiveAndDelete.
    :type mode: ~azure.servicebus.common.constants.ReceiveSettleMode
    :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

    Example:
        .. literalinclude:: ../examples/async_examples/test_examples_async.py
            :start-after: [START open_close_receiver_session_context]
            :end-before: [END open_close_receiver_session_context]
            :language: python
            :dedent: 4
            :caption: Running a session receiver within a context manager.

        .. literalinclude:: ../examples/async_examples/test_examples_async.py
            :start-after: [START open_close_receiver_session_nextavailable]
            :end-before: [END open_close_receiver_session_nextavailable]
            :language: python
            :dedent: 4
            :caption: Running a session receiver for the next available session.

    """

    def __init__(
            self, handler_id, source, auth_config, *, session=None, loop=None,
            connection=None, encoding='UTF-8', debug=False, **kwargs):
        self.session_id = None
        self.session_filter = session
        self.locked_until = None
        self.session_start = None
        self.auto_reconnect = False
        self.auto_renew_error = None
        super(SessionReceiver, self).__init__(
            handler_id, source, 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 = ReceiveClientAsync(
            self._get_source(),
            auth=auth,
            debug=self.debug,
            properties=self.properties,
            error_policy=self.error_policy,
            client_name=self.name,
            on_attach=self._on_attach,
            auto_complete=False,
            encoding=self.encoding,
            loop=self.loop,
            **self.handler_kwargs)

    async def _can_run(self):
        await super(SessionReceiver, self)._can_run()
        if self.expired:
            raise SessionLockExpired(inner_exception=self.auto_renew_error)

    async def _handle_exception(self, exception):
        if isinstance(exception, errors.LinkDetach) and exception.condition == SESSION_LOCK_LOST:
            error = SessionLockExpired("Connection detached - lock on Session {} lost.".format(self.session_id))
            await self.close(exception=error)
            raise error
        elif isinstance(exception, errors.LinkDetach) and exception.condition == SESSION_LOCK_TIMEOUT:
            error = NoActiveSession("Queue has no active session to receive from.")
            await self.close(exception=error)
            raise error
        return await super(SessionReceiver, self)._handle_exception(exception)

    async def _settle_deferred(self, settlement, lock_tokens, dead_letter_details=None):
        message = {
            'disposition-status': settlement,
            'lock-tokens': types.AMQPArray(lock_tokens),
            'session-id': self.session_id}
        if dead_letter_details:
            message.update(dead_letter_details)
        return await self._mgmt_request_response(
            REQUEST_RESPONSE_UPDATE_DISPOSTION_OPERATION,
            message,
            mgmt_handlers.default)

    async def get_session_state(self):
        """Get the session state.

        Returns None if no state has been set.

        :rtype: str

        Example:
            .. literalinclude:: ../examples/async_examples/test_examples_async.py
                :start-after: [START set_session_state]
                :end-before: [END set_session_state]
                :language: python
                :dedent: 4
                :caption: Getting and setting the state of a session.

        """
        await self._can_run()
        response = await self._mgmt_request_response(
            REQUEST_RESPONSE_GET_SESSION_STATE_OPERATION,
            {'session-id': self.session_id},
            mgmt_handlers.default)
        session_state = response.get(b'session-state')
        if isinstance(session_state, six.binary_type):
            session_state = session_state.decode('UTF-8')
        return session_state

    async def set_session_state(self, state):
        """Set the session state.

        :param state: The state value.
        :type state: str or bytes or bytearray

        Example:
            .. literalinclude:: ../examples/async_examples/test_examples_async.py
                :start-after: [START set_session_state]
                :end-before: [END set_session_state]
                :language: python
                :dedent: 4
                :caption: Getting and setting the state of a session.

        """
        await self._can_run()
        state = state.encode(self.encoding) if isinstance(state, six.text_type) else state
        return await self._mgmt_request_response(
            REQUEST_RESPONSE_SET_SESSION_STATE_OPERATION,
            {'session-id': self.session_id, 'session-state': bytearray(state)},
            mgmt_handlers.default)

    async def renew_lock(self):
        """Renew the session lock.

        This operation must be performed periodically in order to retain a lock on the session
        to continue message processing. Once the lock is lost the connection will be closed.
        This operation can also be performed as an asynchronous background task by registering the session
        with an `azure.servicebus.aio.AutoLockRenew` instance.

        Example:
            .. literalinclude:: ../examples/async_examples/test_examples_async.py
                :start-after: [START receiver_renew_session_lock]
                :end-before: [END receiver_renew_session_lock]
                :language: python
                :dedent: 4
                :caption: Renew the sesison lock.

        """
        await self._can_run()
        expiry = await self._mgmt_request_response(
            REQUEST_RESPONSE_RENEW_SESSION_LOCK_OPERATION,
            {'session-id': self.session_id},
            mgmt_handlers.default)
        self.locked_until = datetime.datetime.fromtimestamp(expiry[b'expiration']/1000.0)

    async def peek(self, count=1, start_from=0):
        """Browse messages currently pending in the queue.

        Peeked messages are not removed from queue, nor are they locked.
        They cannot be completed, deferred or dead-lettered.
        This operation will only peek pending messages in the current session.

        :param count: The maximum number of messages to try and peek. The default
         value is 1.
        :type count: int
        :param start_from: A message sequence number from which to start browsing messages.
        :type start_from: int
        :rtype: list[~azure.servicebus.common.message.PeekMessage]

        Example:
            .. literalinclude:: ../examples/async_examples/test_examples_async.py
                :start-after: [START receiver_peek_session_messages]
                :end-before: [END receiver_peek_session_messages]
                :language: python
                :dedent: 8
                :caption: Peek messages in the queue.

        """
        if not start_from:
            start_from = self.last_received or 1
        if int(count) < 1:
            raise ValueError("count must be 1 or greater.")
        if int(start_from) < 1:
            raise ValueError("start_from must be 1 or greater.")

        await self._can_run()
        message = {
            'from-sequence-number': types.AMQPLong(start_from),
            'message-count': count,
            'session-id': self.session_id}
        return await self._mgmt_request_response(
            REQUEST_RESPONSE_PEEK_OPERATION,
            message,
            mgmt_handlers.peek_op)

    async def receive_deferred_messages(self, sequence_numbers, mode=ReceiveSettleMode.PeekLock):
        """Receive messages that have previously been deferred.

        This operation can only receive deferred messages from the current session.
        When receiving deferred messages from a partitioned entity, all of the supplied
        sequence numbers must be messages from the same partition.

        :param sequence_numbers: A list of the sequence numbers of messages that have been
         deferred.
        :type sequence_numbers: list[int]
        :param mode: The receive mode, default value is PeekLock.
        :type mode: ~azure.servicebus.common.constants.ReceiveSettleMode
        :rtype: list[~azure.servicebus.aio.async_message.DeferredMessage]

        Example:
            .. literalinclude:: ../examples/async_examples/test_examples_async.py
                :start-after: [START receiver_defer_session_messages]
                :end-before: [END receiver_defer_session_messages]
                :language: python
                :dedent: 8
                :caption: Defer messages, then retrieve them by sequence number.

        """
        if not sequence_numbers:
            raise ValueError("At least one sequence number must be specified.")
        await self._can_run()
        try:
            receive_mode = mode.value.value
        except AttributeError:
            receive_mode = int(mode)
        message = {
            'sequence-numbers': types.AMQPArray([types.AMQPLong(s) for s in sequence_numbers]),
            'receiver-settle-mode': types.AMQPuInt(receive_mode),
            'session-id': self.session_id
        }
        handler = functools.partial(mgmt_handlers.deferred_message_op, mode=receive_mode, message_type=DeferredMessage)
        messages = await self._mgmt_request_response(
            REQUEST_RESPONSE_RECEIVE_BY_SEQUENCE_NUMBER,
            message,
            handler)
        for m in messages:
            m._receiver = self  # pylint: disable=protected-access
        return messages

    async def list_sessions(self, updated_since=None, max_results=100, skip=0):
        """List session IDs.

        List the IDs of sessions in the queue with pending messages and where the state of the session
        has been updated since the timestamp provided. If no timestamp is provided, all will be returned.
        If the state of a session has never been set, it will not be returned regardless of whether
        there are messages pending.

        :param updated_since: The UTC datetime from which to return updated pending session IDs.
        :type updated_since: ~datetime.datetime
        :param max_results: The maximum number of session IDs to return. Default value is 100.
        :type max_results: int
        :param skip: The page value to jump to. Default value is 0.
        :type skip: int
        :rtype: list[str]
        """
        if int(max_results) < 1:
            raise ValueError("max_results must be 1 or greater.")

        await self._can_run()
        message = {
            'last-updated-time': updated_since or datetime.datetime.utcfromtimestamp(0),
            'skip': skip,
            'top': max_results,
        }
        return await self._mgmt_request_response(
            REQUEST_RESPONSE_GET_MESSAGE_SESSIONS_OPERATION,
            message,
            mgmt_handlers.list_sessions_op)