#!/usr/bin/env python
import optparse
from ZSI.wstools import WSDLTools
from ZSI.wstools.XMLSchema import SchemaReader
from ZSI.wstools.Namespaces import OASIS
from ZSI.wstools.c14n import Canonicalize
from StringIO import StringIO
from ConfigParser import ConfigParser

CP = None

SECTION = 'WSDL'
IMPORTS_SECTION = 'IMPORTS'

# Keys WSDL Section
DEFINITION_KEY = 'definition'
TARGETNAMESPACE_KEY = 'targetNamespace'
SERVICE_KEY = 'service'
SCHEMA_KEY = 'schema'
FILE_KEY = 'file'
FLATTEN_KEY = 'flatten'
PORTS_KEY = 'port_sections'

# Keys for Port sections
PORT_NAME_KEY = 'name'
PORT_LOCATION_KEY = 'location'
PORT_BINDING_KEY = 'binding_section'

# Keys for all Binding sections
BINDING_NAME_KEY = 'name'
BINDING_TYPE_KEY = 'type_section'

# Keys for all PortType sections
PORTTYPE_NAME_KEY = 'name'
PORTTYPE_PROP_KEY = 'properties'
PORTTYPE_OPER_KEY = 'operation_sections'

# Keys for all Operation sections
OPERATION_NAME_KEY = 'name'
OPERATION_INMSG_KEY = 'inputmessage'
OPERATION_OUTMSG_KEY = 'outputmessage'
OPERATION_INMSG_ELEMENT_KEY = 'inputelement'
OPERATION_OUTMSG_ELEMENT_KEY = 'outputelement'
OPERATION_INACTION_KEY = 'inputaction'
OPERATION_OUTACTION_KEY = 'outputaction'


op = optparse.OptionParser()
op.add_option("-c", "--config",
              action="store", dest="config", default=None,
              help="location of configuration file")
(OPTIONS, ARGS) = op.parse_args()
if OPTIONS.config:
    CP = ConfigParser()
    CP.read(OPTIONS.config)


def makeImport(wsdl, targetNamespace, url):
    wsdl.addImport(targetNamespace, url)


def makeMessage(wsdl, other_wsdl_dict, schema, message_name, element):
    msg = wsdl.addMessage(message_name, wsdl.targetNamespace)
    assert schema.elements.has_key(element), \
        'element(%s) is not defined in schema %s' %(element,schema.targetNamespace)
    msg.addPart(name="part", element=(schema.targetNamespace, element))


def makePortType(wsdl, other_wsdl_dict, schema, section, flatten):
    name = CP.get(section, PORTTYPE_NAME_KEY)
    assert name, 'Must specify a portType'

    portType = wsdl.addPortType(name)
    element = CP.get(section, PORTTYPE_PROP_KEY)
    assert schema.elements.has_key(element), \
        'element(%s) is not defined in schema(%s)' %(element,schema.targetNamespace)
    portType.resourceProperties = (schema.targetNamespace, element)

    for op_section in CP.get(section, PORTTYPE_OPER_KEY).split():
        op_name = CP.get(op_section, OPERATION_NAME_KEY)
        input_name = CP.get(op_section, OPERATION_INMSG_KEY)
        output_name = CP.get(op_section, OPERATION_OUTMSG_KEY)

        operation = portType.addOperation(op_name)
        input = operation.setInput(input_name)
        action = CP.get(op_section, OPERATION_INACTION_KEY)
        if action:
            input.action = action
        output = operation.setOutput(output_name)
        action = CP.get(op_section, OPERATION_OUTACTION_KEY)
        if action:
            output.action = action
        if input_name:
            element = CP.get(op_section, OPERATION_INMSG_ELEMENT_KEY)
            makeMessage(wsdl, other_wsdl_dict, schema, input_name, element)
        if output_name:
            element = CP.get(op_section, OPERATION_OUTMSG_ELEMENT_KEY)
            makeMessage(wsdl, other_wsdl_dict, schema, output_name, element)

    return portType


def makeBinding(wsdl, other_wsdl_dict, schema, section, flatten):
    binding_name = CP.get(section, BINDING_NAME_KEY)
    assert binding_name, 'Binding must be specified!!!'

    portType = makePortType(wsdl, other_wsdl_dict, schema, CP.get(section, BINDING_TYPE_KEY), flatten)
    binding = wsdl.addBinding(binding_name, (wsdl.targetNamespace,portType.name))
    binding.addExtension(WSDLTools.SoapBinding(style="document", transport="http://schemas.xmlsoap.org/soap/http"))

    action = portType
    for op in portType.operations:
        soapAction = op.getInputAction()
        op_binding = binding.addOperationBinding(op.name)
        op_binding.addExtension(WSDLTools.SoapOperationBinding(soapAction=soapAction))
        op_binding.addInputBinding(WSDLTools.SoapBodyBinding("literal", wsdl.targetNamespace))
        op_binding.addOutputBinding(WSDLTools.SoapBodyBinding("literal", wsdl.targetNamespace))

    return binding


def makeService(wsdl, other_wsdl_dict, schema, flatten):
    name = CP.get(SECTION, SERVICE_KEY)
    service = wsdl.addService(name, targetNamespace=wsdl.targetNamespace)

    for port_section in CP.get(SECTION, PORTS_KEY).split():
        name = CP.get(port_section, PORT_NAME_KEY)
        assert name not in map(lambda p:p.name, service.ports), \
            'port (%s) already defined!!' %name
        binding = makeBinding(wsdl, other_wsdl_dict, schema, CP.get(port_section,PORT_BINDING_KEY), flatten)
        port = service.addPort(name, (wsdl.targetNamespace,binding.name))
        ext = WSDLTools.SoapAddressBinding(location=CP.get(port_section, PORT_LOCATION_KEY))
        port.addExtension(ext)
    return service


#######################################################

def pretty_print(s):
    token = 'XXX'
    buff = StringIO()
    s1 = s.replace('</', token)
    for i in s1.split('<'):
        if not i: continue
        i = '<%s' %i
        for j in i.split(token):
            if j and j[0] == '<':
                buff.write('\n%s' %j)
            else:
                buff.write('\n</%s' %j)
    return buff.getvalue()



def main():
    """
    FactoryPattern
    Notification
    ResourceProperties
    ResourceLifetime
    """
    # All these parameters should be grabbed from a config file.
    flatten = CP.getboolean(SECTION, FLATTEN_KEY)
    targetNamespace = CP.get(SECTION, TARGETNAMESPACE_KEY)
    schema_location = CP.get(SECTION, SCHEMA_KEY)
    wsdl_file_name = CP.get(SECTION, FILE_KEY)
    definition_name = CP.get(SECTION, DEFINITION_KEY)

    # Other stuff
    other_wsdl_dict = {}
    wsdl = WSDLTools.WSDL(targetNamespace)

    if schema_location:
        schema = SchemaReader().loadFromFile(schema_location)
        makeImport(wsdl, schema.targetNamespace, schema_location)

    for item in CP.items(IMPORTS_SECTION):
        key,value = item
        import_wsdl = WSDLTools.WSDLReader().loadFromFile(value)
        other_wsdl_dict[import_wsdl.targetNamespace] = import_wsdl
        makeImport(wsdl, import_wsdl.targetNamespace, import_wsdl.location)

    # Flatten take all portTypes combine into one.
    makeService(wsdl, other_wsdl_dict, schema, flatten)
    f = open(wsdl_file_name, 'w')
    wsdl.toDom()
    s = pretty_print(Canonicalize(wsdl.document))
    f.write(s)


if __name__ == '__main__':
    main()
