# Copyright 2010 OpenStack Foundation
# 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.

import logging

from six.moves.urllib import parse as urlparse

from keystoneclient import exceptions
from keystoneclient import httpclient
from keystoneclient.i18n import _, _LE


_logger = logging.getLogger(__name__)


class Client(httpclient.HTTPClient):
    """Client for the OpenStack Keystone pre-version calls API.

    :param string endpoint: A user-supplied endpoint URL for the keystone
                            service.
    :param integer timeout: Allows customization of the timeout for client
                            http requests. (optional)

    Example::

        >>> from keystoneclient.generic import client
        >>> root = client.Client(auth_url=KEYSTONE_URL)
        >>> versions = root.discover()
        ...
        >>> from keystoneclient.v2_0 import client as v2client
        >>> keystone = v2client.Client(auth_url=versions['v2.0']['url'])
        ...
        >>> user = keystone.users.get(USER_ID)
        >>> user.delete()

    """

    def __init__(self, endpoint=None, **kwargs):
        """Initialize a new client for the Keystone v2.0 API."""
        super(Client, self).__init__(endpoint=endpoint, **kwargs)
        self.endpoint = endpoint

    def discover(self, url=None):
        """Discover Keystone servers and return API versions supported.

        :param url: optional url to test (without version)

        Returns::

            {
                'message': 'Keystone found at http://127.0.0.1:5000/',
                'v2.0': {
                    'status': 'beta',
                    'url': 'http://127.0.0.1:5000/v2.0/',
                    'id': 'v2.0'
                },
            }

        """
        if url:
            return self._check_keystone_versions(url)
        else:
            return self._local_keystone_exists()

    def _local_keystone_exists(self):
        """Checks if Keystone is available on default local port 35357."""
        results = self._check_keystone_versions("http://localhost:35357")
        if results is None:
            results = self._check_keystone_versions("https://localhost:35357")
        return results

    def _check_keystone_versions(self, url):
        """Calls Keystone URL and detects the available API versions."""