from six.moves.urllib import parse
import keystoneclient
from keystoneclient import client
from rally import osclients

def _get_session(auth_url=None, version=None):
    from keystoneauth1 import discover
    from keystoneauth1 import session
    from keystoneclient.auth import identity

    password_args = {
        "auth_url": "http://keystone:35357/v3",
        "username": "admin",
        "password": "foobar",
        "tenant_name": "admin"
    }

    credential = {
        "auth_url": "http://keystone:35357/v3",
        "username": "admin",
        "password": "foobar",
        "tenant_name": "admin",
        "permission": "user",
        "region_name": None, "endpoint_type": None,
        "domain_name": "admin", "endpoint": None,
        "user_domain_name": None, "admin_domain_name": "Default",
        "project_domain_name": None,
        "https_insecure": False, "https_cacert": None,
    }

    version = osclients.OSClient.get("keystone")(
        credential, {}, {}).choose_version(version)
    if version is None:
        # NOTE(rvasilets): If version not specified than we discover
        # available version with the smallest number. To be able to
        # discover versions we need session
        temp_session = session.Session(
            verify=True, timeout=10.0)
        version = str(discover.Discover(
            temp_session,
            "http://keystone:35357/v3").version_data()[0]["version"][0])

    if "v2.0" not in password_args["auth_url"] and (
            version != "2"):
        password_args.update({
            "user_domain_name": None,
            "domain_name": "admin",
            "project_domain_name": None,
        })
    identity_plugin = identity.Password(**password_args)
    sess = session.Session(
        auth=identity_plugin, verify=True, timeout=10.0)

    return sess, identity_plugin

def _remove_url_version():
    """Remove any version from the auth_url.
    The keystone Client code requires that auth_url be the root url
    if a version override is used.
    """
    url = parse.urlparse("http://keystone:35357/v3")
    # NOTE(bigjools): This assumes that non-versioned URLs have no
    # path component at all.
    parts = (url.scheme, url.netloc, "/", url.params, url.query,
             url.fragment)
    return parse.urlunparse(parts)

version = 3

auth_url = "http://keystone:35357/v3"
if version is not None:
    auth_url = _remove_url_version()
sess, plugin = _get_session(auth_url=auth_url)
# NOTE(bigjools): When using sessions, keystoneclient no longer
# does any pre-auth and calling client.authenticate() with
# sessions is deprecated (it's still possible to call it but if
# endpoint is defined it'll crash). We're forcing that pre-auth
# here because the use of the service_catalog depends on doing
# this. Also note that while the API has got the
# endpoints.list() equivalent, there is no service_type in that
# list which is why we need to ensure service_catalog is still
# present.
auth_ref = plugin.get_access(sess)
print auth_ref