# -*- coding: utf-8 -*-
from __future__ import print_function, absolute_import, division

import getpass
from .log import info, debug, CMDLineExit

try:
    import keyring
except ImportError:  # pragma: no cover
    keyring = None

PROMPT = 'prompt'
KEYRING = 'keyring'
TESTING = 'testing'
PASSWORD_PROVIDERS = [PROMPT, KEYRING, TESTING]


def prompt_get_password(username):
    """Return password for the given user"""
    return getpass.getpass("Password for {0}: ".format(username))


def keyring_get_password(username):
    if keyring is None:
        raise CMDLineExit("You requested to use the 'keyring' module "
                          "as password provider, but do not have this "
                          "installed.")

    keyring_impl = keyring.get_keyring()
    if keyring_impl.__class__.__name__ == 'PlaintextKeyring':
        raise CMDLineExit("Aborting: the 'keyring' module has selected the "
                          "insecure 'PlaintextKeyring'.")

    debug("Note: will use the backend: '{0}'".format(keyring_impl))
    password = keyring.get_password('afp', username)
    if not password:
        info("No password found in keychain, please enter it now to store it.")
        password = prompt_get_password(username)
        keyring.set_password('afp', username, password)
    return password


def get_password(password_provider, username):
    if password_provider == PROMPT:
        password = prompt_get_password(username)
    elif password_provider == KEYRING:
        password = keyring_get_password(username)
    elif password_provider == TESTING:
        password = 'PASSWORD'
    else:
        raise CMDLineExit("'{0}' is not a valid password provider.\n".
                          format(password_provider) +
                          "Valid options are: {0}".
                          format(PASSWORD_PROVIDERS))

    return password

@@ -770,68 +770,665 @@
 g()%0A
+%0A
     
-if keyring_impl.__class__.__name__ == 'PlaintextKeyring'
+# For older 'keyring' module (%3C8.0) implementation where undesirable%0A    # implementations were still permissable. And, for newer ones (%3E=8.0),%0A    # where the 'fail' module is used to denote no available keyrings.%0A    undesirable = %5B'keyring.backends.file.PlaintextKeyring',  # %3C  8.0%0A                   'keyring.backends.file.EncryptedKeyring',  # %3C  8.0%0A                   'keyring.backends.fail.Keyring',           # %3E= 8.0%0A                   %5D%0A    # TODO: there has got to be a better way%0A    description = '.'.join((keyring_impl.__class__.__module__,%0A                            keyring_impl.__class__.__name__))%0A    if description in undesirable
 :%0A  
@@ -1451,16 +1451,29 @@
 ineExit(
+%0A            
 %22Abortin
@@ -1531,52 +1531,49 @@
     
-              %22insecure 'PlaintextKeyring'.%22
+%22undesirable backed: '%25s'.%22 %25 description
 )%0A%0A 

improve checking for undesirable keyring backend