#!/usr/bin/python

""" this is a simple class to read in some xml, and then modify our
html files based on what's in there. 
"""

import string, xml.sax, xml.sax.handler, os, os.path, time
from xml.sax import saxutils, handler, make_parser

class XMLHandler(handler.ContentHandler):
    
    def __init__(self):
        self.data = ""
        self.delegate = None
        self.atts = {}
        self.pages = []
        self.documentName = ""
        self.documentUUID = ""
        self.webExportProperties = ""
    
    def startElement(self, name, attrs):
        self.data = ""
    
    def endElement(self, name):
        
        if name == "page":
            self.pages.append((self.atts['createDate'], self.atts['fileName'], self.atts['displayName'], self.atts['modifiedDate'], self.atts['uuid'], self.atts['version']))
            
            self.atts.clear()
        
        elif name == "documentName":
            self.documentName = self.data
        
        elif name == "documentUUID":
            self.documentUUID = self.data
        
        elif name == "webExportProperties":
            self.webExportProperties = self.data
        
        else:
            self.atts[name] = self.data
        
    def characters(self, ch):
        self.data += ch
    
def parseProps(s):
    
    props = {}
    
    for line in s.splitlines():
        line = string.strip(line)
        
        if line.strip().startswith("#"):
            continue
        
        eqIndex = string.find(line, "=")
        
        if (eqIndex > 0):
            key = line[0:eqIndex]
            value = line[eqIndex+1:]
            props[key] = value
        else:
            #print "ignoring " + line
            pass
    
    return props
    

def main():
    
    outputDir   = os.environ.get('VPWebExportOutputDirectory')
    
    if outputDir is None:
        print "Can't find the xml file, aborting"
        return
    
    myTemplate = open(os.environ.get('VPWebExportPluginDirectory') + "/Contents/template.html").read()
    
    metaFile = outputDir + "/meta.xml"
    
    f = open(metaFile)
    
    xh = XMLHandler()
    
    # parse the sucker.
    xml.sax.parseString(f.read(), xh)
    
    xh.pages.sort()
    xh.pages.reverse()
    count = 0
    props = parseProps(xh.webExportProperties)
    
    indexPage = ""
    
    lmod = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.localtime())
    
    atomFeed  = """<?xml version="1.0" encoding="utf-8"?>
     <feed xmlns="http://www.w3.org/2005/Atom">

     <title>%s</title>
     <link href="%s" rel="self"/>
     <updated>%s</updated>
     <author>
       <name>%s</name>
     </author>
     <id>urn:uuid:%s</id>""" % (xh.documentName, props.get('blogUrl', '') + 'atom.xml', lmod, xh.documentName, xh.documentUUID)
    
    for pageInfo in xh.pages:
        
        pageDict     = {'createDate': pageInfo[0],
                        'fileName':   pageInfo[1],
                        'displayName': pageInfo[2],
                        'modifiedDate': pageInfo[3],
                        'uuid':         pageInfo[4],
                        'version':      pageInfo[5]}
        
        theTime      = time.localtime(float(pageDict['createDate']))
        modTime      = time.localtime(float(pageDict['modifiedDate']))
        
        fancyDate    = time.strftime('%B %d, %Y', theTime)
        botDate      = time.strftime('%r', theTime)
        fancyModDate = time.strftime('%B %d, %Y at %r', modTime)
        
        pageDict['fancyDate']    = fancyDate
        pageDict['botDate']      = botDate
        pageDict['fancyModDate'] = fancyModDate
        pageDict['fileURL']      = string.replace(props.get('blogUrl', '') + pageDict['fileName'], ' ', '%20')
        
        timeFormat = "%Y-%m-%dT%H:%M:%SZ"
        
        pageDict['atomModifiedDate'] = time.strftime(timeFormat, theTime)
        pageDict['atomCreateDate']   = time.strftime(timeFormat, modTime)
        
        
        if pageDict['fileName'] == "index.html":
            continue
        
        if count >= 15:
            break
        
        page = open(outputDir + "/" + pageDict['fileName']).read()
        
        pageStartIdx = page.index("<!-- pageStart -->") + 18
        pageEndIdx = page.index("<!-- pageEnd -->")
        
        entry = page[pageStartIdx:pageEndIdx]
        
        pageDict['entry'] = entry
        pageDict['entryEscaped'] = saxutils.escape(entry)
        
        indexPage += '''<div class="entry" style="padding-bottom: 20px;">
                            <div style="font-size: 1.1em; font-weight:bold;"><a href="%(fileName)s" >%(displayName)s</a></div>
                            <div style="font-size: .9em; padding-bottom: 12px;">%(fancyDate)s</div>
                            %(entry)s
                            <div style="font-size: .9em; padding-top: 5px;">%(botDate)s<br/>Last modified %(fancyModDate)s</div>
                        </div>
            \n''' % pageDict
        
        
        atomFeed +=  """  <entry>
           <title>%(displayName)s</title>
           <link href="%(fileURL)s" />
           <id>urn:uuid:%(uuid)s:%(version)s</id>
           <updated>%(atomModifiedDate)s</updated>
           <content type="html">%(entryEscaped)s</content>
         </entry>\n""" % pageDict
        
        count = count + 1
    
    atomFeed += "</feed>"
    
    myTemplate = myTemplate.replace("$page$", indexPage)
    myTemplate = myTemplate.replace("$categories$", "")
    myTemplate = myTemplate.replace("$title$", props.get('blogTitle', ''))
    
    # put in our feed link
    myTemplate = myTemplate.replace('</title>', '</title>\n<link rel="alternate" type="application/atom+xml" title="atom" href="atom.xml" />\n')
    
    out = open(outputDir + '/index.html', 'w')
    out.write(myTemplate)
    out.close()
    
    
    out = open(outputDir + '/atom.xml', 'w')
    out.write(atomFeed)
    out.close()
    
    

if __name__ == '__main__':
    main()