############################################################################
# Monte M. Goode, LBNL
# See LBNLCopyright for copyright notice!
###########################################################################

# utility classes used by new generator - mostly 'sugar' classes
# that are actually imported by the generated code.  also includes
# utilities used by wsdl2python itself.

# $Id$

import re
from ZSI import EvaluateException
from ZSI.TCcompound import Struct
from ZSI.generate import WsdlGeneratorError, Wsdl2PythonError
from ZSI.wstools.Utility import SplitQName

NCName_to_ModuleName = lambda name: re.sub('\.', '_', TextProtect(name))
NCName_to_ClassName = lambda name: re.sub('\.', '_', TextProtect(name))
TextProtect = lambda s: re.sub('[-./:# ]', '_', s)
TextProtectAttributeName = lambda name: TextProtect('_%s' %name)
Namespace2ModuleName = lambda ns: TextProtect(ns.lstrip('http://')).rstrip('_')


def GetModuleBaseNameFromWSDL(wsdl):
    """By default try to construct a reasonable base name for all
    generated modules.  Otherwise return None.
    """
    base_name = wsdl.name or wsdl.services[0].name
    base_name = SplitQName(base_name)[1]
    if base_name is None: 
        return None
    return NCName_to_ModuleName(base_name)

namespace_name = lambda cls, ns: 'ns%s' % len(cls.alias_list)

class NamespaceAliasDict:
    """a lookup table to store relevant namespaces and their aliases"""
    alias_dict = {}
    alias_list = []

    def add(cls, ns):
        if cls.alias_dict.has_key(ns):
            return
        cls.alias_dict[ns] = (Namespace2ModuleName(ns), '%s' % namespace_name(cls,ns))
        cls.alias_list.append(ns)
    add = classmethod(add)
            
    def getModuleName(cls, ns):
        if cls.alias_dict.has_key(ns):
            return cls.alias_dict[ns][0]
        raise WsdlGeneratorError, 'could not retrieve mod name for %s' %ns
    getModuleName = classmethod(getModuleName)
        
    def getAlias(cls, ns):
        if cls.alias_dict.has_key(ns):
            return cls.alias_dict[ns][1]
        raise WsdlGeneratorError, 'could not retrieve alias for %s\t%s' %(ns,cls.alias_dict)
    getAlias = classmethod(getAlias)

    def getNSList(cls):
        return tuple(cls.alias_list)
    getNSList = classmethod(getNSList)


class StringWriter:
    """generator util"""
    def __init__(self, val=None):
        self.data = []
        if val:
            self.data.append(val)

    def set(self, val):
        if self.data:
            # in some cases the empty list reassignment fails, so....
            self.data = None
            self.data = []

        self.data.append(val)

    def write(self, val):
        self.data.append(val)

    def getvalue(self):
        if self.data:
            return ''.join(self.data)
        else:
            return ''

    def __iadd__(self, val):
        self.data.append(val)
        return self

    def __str__(self):
        return self.getvalue()


# ---- generated code utils

class MessageContainer:
    """generator util - used by address.py"""
    pass

# Extract sub names from message parts so they can be used when mapping
#    a message's contents to a function's arguments.
# Args is a list of Message Parts.  i.e.: op.getInputMessage().parts.values()
def GetPartsSubNames(args, wsdl):
    do_extended = True
    from wsdl2python import WriteServiceModule, SchemaDescription
    wsm = WriteServiceModule(wsdl, do_extended=do_extended)
    wsm.gatherNamespaces()
    toReturn = []
    for arg in args:
        argSubnames = []
        for l in wsm.usedNamespaces.values():
            for schema in l:
                sd = SchemaDescription(do_extended=do_extended)
                sd.fromSchema(schema)
                argNamespace = arg.element[0]
                if (sd.targetNamespace == argNamespace):
                    for i in sd.items:
                        # arg.name is the part name, but we want it's type
                        argElementType = arg.element[1]
                        if str(argElementType) == str(i.content.name):
                            argSubnames = []
			    # I'm not sure when the name attribute was dropped
			    # but at some point, or in some circumstance it's not
			    # there, but instead a ref attribute is there which is
		     	    # tuple of (namespace, name). This hack fixes things, 
			    # but I'm not sure why this happens or has happened.
			    # IRJ - 2005-05-25
                            for c in i.content.mgContent:
                                nValue = "None"
                                if c.isWildCard():
                                    nValue="any"
                                elif c.attributes.has_key("name"):
                                    nValue = c.attributes["name"]
                                elif c.attributes.has_key("ref"):
                                    nValue = c.attributes["ref"][1]
                                argSubnames.append(nValue)

        toReturn.append(argSubnames)
    return toReturn

@@ -4444,16 +4444,80 @@
 5-05-25%0A
+                            if i.content.mgContent != None:%0A    
         
@@ -4590,32 +4590,36 @@
                 
+    
 nValue = %22None%22%0A
@@ -4618,16 +4618,20 @@
  %22None%22%0A
+    
         
@@ -4705,24 +4705,28 @@
             
+    
 nValue=%22any%22
@@ -4726,16 +4726,20 @@
 e=%22any%22%0A
+    
         
@@ -4793,24 +4793,28 @@
 ey(%22name%22):%0A
+    
             
@@ -4891,32 +4891,36 @@
                 
+    
 elif c.attribute
@@ -4965,32 +4965,36 @@
                 
+    
 nValue = c.attri
@@ -5005,24 +5005,28 @@
 s%5B%22ref%22%5D%5B1%5D%0A
+    
             

Add an if statement to handle when mgContent's value is None. The value used to be set to an empty tuple when there was no content.