import types
import textwrap
import inspect
import sys
import importlib
import string
from random import choice

from jinja2 import Template
from docopt import docopt
from cmd3.shell import command
from cloudmesh.util.util import path_expand, yn_choice
from cloudmesh.user.cm_user import cm_user



from cloudmesh.util.logger import LOGGER

log = LOGGER(__file__)

# Helpers
def generate_password():
    """Credit: http://stackoverflow.com/questions/3854692/generate-password-in-python"""
    chars = string.letters + string.digits
    length = 12
    return ''.join([choice(chars) for _ in range(length)])

def create_user_in_cloud(username, password, cloudname):
    print "Create user {0} in {1}".format(username, cloudname)

def user_exists_in_cloud(username, cloudname):
    return False

def get_user_profile(username):
    cmu = cm_user()
    profile = cmu.info('astreib')
    return profile

class cm_shell_admin:

    """Administrative class"""

    def activate_cm_shell_admin(self):
        pass

    @command
    def do_admin(self, args, arguments):
        """
        Usage:
               admin [force] newuser USERNAME CLOUDNAME CONFIGDIR
               
        Initializes new user in the CLOUDNAME cloud. A cloudmesh.yaml
        file will be generated and placed in CONFIGDIR.

        Arguments:

          newuser    create a new user

          USERNAME   the username of the new user

          CLOUDNAME  the name of the cloud
          
          CONFIGDIR  where to place the cloudmesh.yaml file

          force      force mode does not ask. This may be dangerous.

        Options:
           
           -v       verbose mode

        """
        log.info(arguments)
        print "<", args, ">"

        if arguments["newuser"]:

            new_username = arguments["USERNAME"]
            cloudname = arguments["CLOUDNAME"]
            configdir = arguments["CONFIGDIR"]

            cm_yaml = path_expand('{0}/cloudmesh.yaml'.format(configdir))
            etc_yaml = path_expand("~/.futuregrid/etc/cloudmesh.yaml")
            me_yaml = path_expand("~/.futuregrid/etc/me.yaml")

            if user_exists_in_cloud(new_username, cloudname):
                print "User {0} is already defined in cloud {1}".format(new_username, cloudname)
            else:
                me_values = get_user_profile(new_username)
                new_password = generate_password()
                create_user_in_cloud(new_username, new_password, cloudname)

                me_content = open(me_yaml, 'r').read()
                me_values["passwords"] = { cloudname: new_password }
                t = Template(me_content)
                print t.render(**me_values)

            return






@@ -289,16 +289,68 @@
 cm_user%0A
+from cloudmesh.iaas.openstack.cm_idm import keystone
 %0A%0A%0Afrom 
@@ -657,117 +657,347 @@
 %5D)%0A%0A
-def create_user_in_cloud(username, password, cloudname):%0A    print %22Create user %7B0%7D in %7B1%7D%22.format(username, 
+class cm_shell_admin:%0A%0A    %22%22%22Administrative class%22%22%22%0A%0A    def __init__(self):%0A        self._keystones = %7B %7D%0A%0A    def activate_cm_shell_admin(self):%0A        pass%0A%0A    def get_keystone(self, cloudname):%0A        if cloudname not in self._keystones:%0A            self._keystones%5Bcloudname%5D = keystone(cloudname)%0A        return self._keystones%5B
 clou
@@ -1001,19 +1001,23 @@
 loudname
-)
+%5D
 %0A%0A
+    
 def user
@@ -1033,16 +1033,22 @@
 n_cloud(
+self, 
 username
@@ -1069,22 +1069,126 @@
     
-return False%0A%0A
+    k = self.get_keystone(cloudname)%0A        k_id = k.get_user_by_name(username)%0A        return not k_id is None%0A%0A    
 def 
@@ -1204,16 +1204,22 @@
 profile(
+self, 
 username
@@ -1217,24 +1217,28 @@
  username):%0A
+    
     cmu = cm
@@ -1249,16 +1249,20 @@
 r()%0A    
+ 
+   
 profile 
@@ -1276,19 +1276,22 @@
 nfo(
-'astreib')%0A
+username)%0A    
     
@@ -1310,114 +1310,145 @@
 le%0A%0A
-class cm_shell_admin:%0A%0A    %22%22%22Administrative class%22%22%22%0A%0A    def activate_cm_shell_admin(self):%0A        pass
+    def create_user_in_keystone(self, username, password, cloudname):%0A        print %22Create user %7B0%7D in %7B1%7D%22.format(username, cloudname)%0A
 %0A%0A  
@@ -2566,16 +2566,21 @@
      if 
+self.
 user_exi
@@ -2761,16 +2761,21 @@
 alues = 
+self.
 get_user
@@ -2860,24 +2860,29 @@
             
+self.
 create_user_
@@ -2880,29 +2880,32 @@
 ate_user_in_
-cloud
+keystone
 (new_usernam
@@ -3162,13 +3162,8 @@
  return%0A
-%0A%0A%0A%0A%0A

Use keystone to check for users already existing