#!/usr/bin/python
import time, sha, sys, codecs, string, base64, urlparse, urllib2, httplib, random
import xmltramp, types
import xmlrpclib
import socket

import os.path
import sys, traceback, StringIO

sys.stdout = codecs.getwriter('utf8')(sys.stdout)

#data['content'] = escape(str(post.content))
#data['title']   = escape(str(post.title))

def escape(s):
    
    if type(s) == types.StringType:
        s = s.replace("&", "&amp;")
        s = s.replace("<", "&lt;")
        s = s.replace(">", "&gt;")
    
    elif type(s) == types.UnicodeType:
        s = s.replace("&", "&amp;")
        s = s.replace("<", "&lt;")
        s = s.replace(">", "&gt;")
        
    
    return s

def getDisplayName():
    
    return "<vp><displayName>VPWiki 0.1</displayName></vp>"

def savePage():
    
    
    #rtfFile = open('/Volumes/srv/Users/gus/myfile.rtf', 'w')
    #rtfFile.write(base64.decodestring(str(request.vpdata)))
    
    vpwiki = xmlrpclib.Server(str(request.endPoint)).vpwiki
    
    login = {'name':        str(request.username),
             'password':    str(request.password)}
    
    pageStruct = {'key': request.key[0],
                  'page':request.pageAsPlainText[0],
                  'wikiPage':request.pageAsTextileText[0],
                  'data': xmlrpclib.Binary(base64.decodestring(request.pageAsRTFD[0])),
                  'version': int(request.version[0]),
                  'title': request.title[0],
                 }
    
    if vpwiki.setPage(login, pageStruct):
        if len(request.imagePaths) > 0:
            
            try:
                for file in request.imagePaths[0].split('|'):
                    
                    imageData = open(file).read()
                    
                    d = {'fileName': os.path.basename(file),
                         'file': xmlrpclib.Binary(imageData) }
                    
                    vpwiki.putAttachment(login, request.key[0], d)
                
            except:
                pass
                #return """<vp><error>Sorry, I could not upload the images\n\n</error></vp>""" % s
        
        return "<vp><savePageResponse>true</savePageResponse></vp>"
                
    else:
        return "<vp><savePageResponse>false</savePageResponse></vp>"


def getPageNames():
    
    #time.sleep(20)
    
    vpwiki = xmlrpclib.Server(str(request.endPoint)).vpwiki
    
    login = {'name':    str(request.username),
             'password':str(request.password)
            }
    
    pageKeys = vpwiki.getAllKeys(login)
    
    s = """<vp>
    <getPageNamesResponse>"""
    
    for page in pageKeys:
        s += """        <pageName>%s</pageName>""" % (escape(page))
    
    s += """    </getPageNamesResponse>
</vp>"""
    
    return s

def getDefaultPageName():
    return "<vp><getDefaultPageNameResponse>index</getDefaultPageNameResponse></vp>" 


def getDefaultPage():
    return getPageInternal()


def getPage():
    return getPageInternal(string.lower(str(request.key)))


def getPageInternal(key="index"):
    vpwiki = xmlrpclib.Server(str(request.endPoint)).vpwiki
    
    login = {'name':    str(request.username),
             'password':str(request.password)
            }
    
    key   = key.lower()
    
    pageStruct = vpwiki.getPage(login, key)
    
    #fixme - what should we do if no page is given?
    
    if not pageStruct.has_key("version"):
        pageStruct['version'] = "0"
        
    if not pageStruct.has_key("lastModified"):
        pageStruct['lastModified'] = "0"
        
    if not pageStruct.has_key("rulerIsShowing"):
        pageStruct['rulerIsShowing'] = False
        
    if not pageStruct.has_key("title"):
        pageStruct['title'] = key
    
    if not pageStruct.has_key("alias"):
        pageStruct['alias'] = key
        
    if not pageStruct.has_key("data"):
        pageStruct['data'] = ""
    else:
        pageStruct['data'] = base64.encodestring(str(pageStruct['data']))
    
    for key in pageStruct.keys():
        pageStruct[key] = escape(pageStruct[key])
    
    
    
    
    #time.sleep(10)
    
    #open("/tmp/pout", 'w').write(pageStruct['page'])
    
    s = """<vp>
    <getPageResponse>
        <key>%(key)s</key>
        <version>%(version)s</version>
        <lastModified>%(lastModified)s</lastModified>
        <rulerIsShowing>%(rulerIsShowing)s</rulerIsShowing>
        <title>%(title)s</title>
        <pageAsPlainText>%(page)s</pageAsPlainText>
        <pageAsRTFD>%(data)s</pageAsRTFD>
        <alias>%(alias)s</alias>
    </getPageResponse>
</vp>""" % pageStruct

    return s
    
    
def main(args = sys.argv):
    
    print eval(str(request.action) + "()")
    
    '''
    try:
        # just call a function of the name of whatever the action is.
        print eval(str(request.action) + "()")
    
    except socket.error:
        print """<vp><error>Sorry, but I could not connect to the server</error></vp>"""
    except:
        print """<vp><error>Sorry, and unknown error has occured</error></vp>"""
    '''
    
#time.sleep(5)

# read in our xml.
xml = sys.stdin.read();
request = xmltramp.parse(xml)

#open("/tmp/pout", 'w').write(xml)
    

if __name__ == "__main__":
    main()

