#!/usr/bin/python2
#
# wa-indexgen 
#
# A script to generate index pages for kde web applets.
# It uses descriptiondata encoded in the web applet
# page to generate the index
#
import getopt, sys
import xml.parsers.expat

output_file = None
args = []
try:
    opts, args = getopt.getopt(sys.argv[1:], "ho:", ["help","output-file="])
except getopt.GetoptError:
    # print help information and exit:
    usage()
    sys.exit(2)
    output = None
else:
    for o, a in opts:
        if o in ("-h", "--help"):
            usage()
            sys.exit()
        if o in ("-o", "--ouput-file"):
            output_file = a

def usage():
    print "Usage: wa-indexgen -f <config file> [-o output file]"

curfield = None

def parse_file(inf):
    result = {}
    fields = ['name','image','url','description']

    # 3 handler functions
    def start_element(name, attrs):
        global curfield
        if attrs.has_key('id') and attrs['id'] in fields:
            curfield = attrs['id']
        
    def end_element(name):
        global curfield
        curfield = None
            
    def char_data(data):
        global curfield
        if not curfield is None:
            result[curfield] = str(data)

    p = xml.parsers.expat.ParserCreate()

    p.StartElementHandler = start_element
    p.EndElementHandler = end_element
    p.CharacterDataHandler = char_data

    p.ParseFile(open(inf,"r"))

    return result

applets = []
for ifile in args:
    applets.append(parse_file(ifile))
    
if not output_file is None:
    sys.stdout = open(output_file,"w")

print """<html>
  <head>
    <style>"""
style = """
body {
	border: 0px 0px 0px 0px;
	padding: 0px 0px 0px 0px;
	margin: 0px 0px 0px 0px;
	background: white;
	color: black;
	font-family: Verdana, Arial, sans-serif;
	font-size: 8pt;
}
a {
	color: black;
	text-decoration: none;
}
a:visited {
	color: black;
}
a:current {
	color: black;
}
a:hover {
	background: rgb(225,235,240);
}
h2 {
	background-color: rgb(210,230,240);
	font-size: 17pt;
}
img {
        border: 0px;
}"""

print style.replace("\n","\n      ")
print """    </style>
  </head>
  <body>"""

ind = 4
def indent(d):
    global ind
    ind += d
    res = " " * ind
    return res

try:
    for i in applets:
        print indent(0) + '<table cellspacing="0" cellpadding="0" width="100%">'
        print indent(2) + '<tr>'
        print indent(2) + '<td>'
        
        print indent(2) + "<a href=\"" + i['url'].strip() + "\"",
        
        print "><h2><img width=\"21\" height=\"21\"",
        print  "src=\"" + i['image'].strip() + "\"/ >&nbsp;",
        
        print i['name'].strip() + "</h2>\n" + indent(2) + "<p>",
        print i['description'].strip(),
        print "</p>"
        print indent(0) + "<br>"
        print indent(-2) + "</a>"
        print indent(-2) + "</td>"
        print indent(-2) + "</tr>"
        print indent(-2) + "</table>"
except StandardError, e:
    print "Error :" + str(e)

print "  </body>\n</html>";

