import types
import textwrap
from docopt import docopt
import inspect
import sys
import importlib
from cmd3.shell import command
from pprint import pprint
from cloudmesh.inventory import Inventory
from mongoengine import *

from cloudmesh_common.logger import LOGGER
log = LOGGER(__file__)


class cm_shell_inventory:

    """opt_example class"""

    def info_cm_shell_inventory(self):
        print "%20s =" % "DBNAME", self.inventory_name

    def activate_cm_shell_inventory(self):
        self.register_command_topic('cloud','inventory')
        #
        # BUG this needs to be done not in activate
        #
        self.inventory_name = "test"
        # port number is missing
        # should be imported from cloudmesh_server.yaml
        db = connect(self.inventory_name)

        self.inventory = Inventory()
        pass

    @command
    def do_inventory(self, args, arguments):
        """
        Usage:
               inventory clean
               inventory create image DESCRIPTION
               inventory create server [dynamic] DESCRIPTION
               inventory create service [dynamic] DESCRIPTION
               inventory exists server NAME
               inventory exists service NAME
               inventory
               inventory print
               inventory info [--cluster=CLUSTER] [--server=SERVER]
               inventory list [--cluster=CLUSTER] [--server=SERVER]
               inventory server NAME
               inventory service NAME

        Manages the inventory

            clean       cleans the inventory
            server      define servers

        Arguments:

          DESCRIPTION    The hostlist"i[009-011],i[001-002]"

          NAME           The name of a service or server


        Options:

           v       verbose mode

        """
        #if arguments["v"]:
        log.info(arguments)
        log.info(args)

        if args == "":
            log.info("print inventory")

        if arguments["clean"]:
            log.info("clean the inventory")
            return

        if arguments["print"]:
            log.info("print the inventory")
            r = self.inventory.find({})
            for e in r:
                pprint(e)

            return

        if arguments["info"]:
            print
            print "Inventory Information"
            print "---------------------"
            print
            if not (arguments["--cluster"] or arguments["--server"]):

                print self.inventory.info()
                print

            if arguments["--cluster"] and not arguments["--server"]:

                name = arguments["--cluster"]

                r = self.inventory.cluster(name)
                pprint(r)

            return

        for kind in ["server", "service", "image"]:
            if arguments["info"] and arguments[kind]:
                name = arguments["NAME"]
                kind = arguments[kind]
                self.inventory.print_kind(serv, name)
                return

        if arguments["create"] and arguments["server"]:
            hostlist = arguments["DESCRIPTION"]
            log.info("create servers" + hostlist)
            return

        if arguments["create"] and arguments["service"]:
            hostlist = arguments["DESCRIPTION"]
            log.info("create services" + hostlist)
            return

        if arguments["exists"] and arguments["server"]:
            name = arguments["NAME"]
            if self.inventory.exists("server", name):
                print "true"
            else:
                print "false"
            return

        if arguments["exists"] and arguments["service"]:
            name = arguments["NAME"]
            if self.inventory.exists("service", name):
                print "true"
            else:
                print "false"
            return

@@ -341,16 +341,80 @@
 ass%22%22%22%0A%0A
+    inventory_connection = False%0A    inventory_name = None%0A    %0A
     def 
@@ -474,14 +474,22 @@
  %25 %22
-DBNAME
+inventory_name
 %22, s
@@ -511,97 +511,104 @@
 ame%0A
-%0A
     
-def activate_cm_shell_inventory(self):%0A        self.register_command_topic('cloud','
+    print %22%2520s =%22 %25 %22inventory_connection%22, self.inventory_connection%0A%0A    def _connect_to_
 inve
@@ -616,10 +616,15 @@
 tory
-')
+(self):
 %0A   
@@ -632,71 +632,78 @@
     
-#%0A        # BUG this needs to be done not in activate%0A        #
+%22%22%22connects to the inventory and prints an error if not successfull%22%22%22
 %0A   
@@ -744,17 +744,40 @@
         
-#
+try:%0A            # TODO:
  port nu
@@ -800,17 +800,27 @@
         
+ 
-#
+   # TODO:
  should 
@@ -866,16 +866,20 @@
         
+ 
+   
 db = con
@@ -904,25 +904,25 @@
 y_name)%0A
-%0A
+ 
         
 self.inv
@@ -905,32 +905,35 @@
 _name)%0A         
+   
 self.inventory =
@@ -945,16 +945,348 @@
 ntory()%0A
+        except:%0A            self.Inventory = None%0A            raise Exception(%22ERROR: connection to inventory failed%22)%0A%0A        %0A    def activate_cm_shell_inventory(self):%0A        self.register_command_topic('cloud','inventory')%0A        try:%0A            self._connect_to_inventory()%0A        except Exception, e:%0A            print e%0A
         
@@ -2523,24 +2523,95 @@
 s%5B%22print%22%5D:%0A
+            try:%0A                self._coonnect_to_inventory(self)%0A    
             
@@ -2634,32 +2634,61 @@
 the inventory%22)%0A
+                try:%0A        
             r = 
@@ -2719,24 +2719,32 @@
             
+        
 for e in r:%0A
@@ -2755,24 +2755,32 @@
             
+   
+     
 pprint(e)%0A%0A 
@@ -2777,35 +2777,215 @@
 rint(e)%0A
-%0A            return
+                except:%0A                    raise Exception(%22Error: problem searching the inventory%22)%0A%0A            except Exception, e:%0A                print e%0A%0A            return                    
 %0A%0A      
@@ -3382,16 +3382,20 @@
 uster%22%5D%0A
+    
 %0A       

remove the inventory startup from the activation code. Introduction of exception handeling upon connection.