import urllib;
import xml.dom.minidom

FISHEYE_HOST="http://localhost:8080/"

def callFishEye(methodname, **args):
    data = urllib.urlencode(args)
    fp = urllib.urlopen(FISHEYE_HOST+"api/rest/"+methodname, data)
    doc = xml.dom.minidom.parse(fp)
    fp.close()
    doc.normalize()
    root = doc.documentElement
    if root.tagName == "response":
        return ElementWrapper(root)
    raise Exception, root.toxml()

# a very dodgy helper wrapper around DOM elements
class ElementWrapper:
    def __init__(self, element):
        self.element = element
    def __getitem__(self, key):
        k = key
        list = None
        if k[-7:] == "__array":
            k = k[:-7]
            list = []
        elif self.element.hasAttribute(k):
            # look for an attribute
            return self.element.getAttribute(k)
        for node in self.element.childNodes:
            if node.nodeType == node.ELEMENT_NODE and node.tagName == k:
                if list is None: return ElementWrapper(node)
                list.append(ElementWrapper(node))
        return list

    def has_key(self, key):
        return self[key] is not None
    
    def __repr__(self):
        return self.element.toxml()
    def __str__(self):
        rc = ""
        for node in self.element.childNodes:
            if node.nodeType == node.TEXT_NODE:
                rc = rc + node.data
        return rc


auth = ""
#auth = callFishEye("login", username="username", password="password")['string']
print "Using auth:", auth

reps = callFishEye("repositories", auth=auth)['string__array']
print "found %i repositories" % len(reps)
print reps

rep = reps[0]
rc = callFishEye("changesets", auth=auth, rep=rep, path='/')['changesets']
print "recent changes:"
csids = rc['csids']['string__array']
print "maxReturn=", rc['maxReturn'], "returned=", len(csids)


csid = csids[0]

cs = callFishEye('changeset', auth=auth, rep=rep, csid=csid)['changeset']
print "changeset", cs['csid']
print "author %s, date %s, branch %s" % (cs['author'], cs['date'], cs['branch'])
print cs['log']
lastFile = None
for ri in cs['revisions']['revisionkey__array']:
    print "- %s %s" % (ri['path'], ri['rev'])
    lastFile = ri['path']


print "looking at", lastFile
hist = callFishEye('pathHistory', auth=auth, rep=rep, path=lastFile)['history']
for r in hist['revisions']['revision__array']:
    print r['rev'], r['author'], r['date']
    if r.has_key('csid'): print r['csid']
    if r.has_key('ancestor'): print r['ancestor']
    print r['log']

    r2 = callFishEye('revision', auth=auth, rep=rep, path=lastFile, rev=r['rev'])['revision']
    assert r2['rev'] == r['rev']
    

print "trying logout:", callFishEye('logout', auth=auth)['boolean']
print "listing reps after logout:", callFishEye("repositories", auth=auth)

