import suds.sudsobject
from django.utils.encoding import force_str


def client_to_jsondict(client):
    """return description of the client, as dict (for json export)"""
    res = {}
    for sd in client.sd:
        d = {}
        d['tns'] = sd.wsdl.tns[1]
        d['prefixes'] = dict(p for p in sd.prefixes)
        d['ports'] = {}
        for p in sd.ports:
            d['ports'][p[0].name] = {}
            for m in p[1]:
                d['ports'][p[0].name][m[0]] = {mp[0]: sd.xlate(mp[1]) for mp in m[1]}
        d['types'] = {}
        for t in sd.types:
            ft = client.factory.create(sd.xlate(t[0]))
            d['types'][sd.xlate(t[0])] = force_str(ft)
        res[sd.service.name] = d
    return res


def sudsobject_to_dict(sudsobject):
    out = {}
    for key, value in suds.sudsobject.asdict(sudsobject).items():
        if hasattr(value, '__keylist__'):
            out[key] = sudsobject_to_dict(value)
        elif isinstance(value, list):
            out[key] = []
            for item in value:
                if hasattr(item, '__keylist__'):
                    out[key].append(sudsobject_to_dict(item))
                else:
                    out[key].append(item)
        else:
            out[key] = value
    return out
