#!/usr/bin/env python

import os, string, glob, time

PROJECTTEMPLATE = 'index.template'
PROJECTINDEX = 'index.shtml'


class Project:
    def __init__(self, filename):
        if not os.path.isfile(filename):
            raise OSError, "No Such Filename"
        self.filename = filename
        self.name = os.path.splitext(os.path.split(filename)[-1])[0]
        self.name = string.upper(self.name)
        self.image = os.path.splitext(filename)[0] + '.jpg'
        if not os.path.isfile(self.image):
            self.image = None
	self.files = []
	for file in glob.glob(os.path.splitext(filename)[0]+'*'):
	    ext = os.path.splitext(file)[1]
	    if ext=='.jpg' or ext=='.txt' or file[-1]=='~': continue
	    self.files.append(os.path.split(file)[1])

        self._defaults()
        self._readfile()


    def __cmp__(self, other):
        format = '%B %d, %Y'
	if self.date: selftime = time.mktime(time.strptime(self.date, format))
	else: selftime = 0.0
	if other.date: othertime = time.mktime(time.strptime(other.date, format))
	else: othertime = 0.0
	return cmp(selftime, othertime)


    def _defaults(self):
        self.version = 'Unknown'
        self.author = 'Unknown'
        self.status = 'Unknown'
	self.date = None
        self.description = 'No Description'
        self.table = 'author', 'date'


    def _readfile(self):
        vals = {'description': ''}
        for line in open(self.filename).readlines():
            line = string.rstrip(line)
            if -1 < string.find(line, '=') < 10:
                key, val = string.split(line, '=')
                if val == 'None': val = None
                vals[string.lower(key)] = val
            else:
                vals['description'] = vals['description'] + line + '\n'

        self.__dict__.update(vals)


    def _wrapinurl(self, str):
    	url = 'games/' + str
        return "<a href=%s>%s</a>" % (url, str)


    def fullhtml(self):
        lines = []
	lines.append("<a name=%s>" % self.name)
        lines.append("<table width=100%><tr valign=top><td width=200 height=150>")
        if self.image:
            lines.append("<img src=%s width=200 height=150 alt=%s>" %
                         (self.image, self.name))
        else:
            lines.append("<big>No Image Available</big>")
        lines.append("</td><td><td><font size=+2><b>")
        lines.append(self.name)
	lines.append("</b></font><br>")
	for f in self.files:
		lines.append(self._wrapinurl(f) + ' ')
        lines.append("<table border=1 cellspacing=0 width=100%>")
        lines.append("<tr><td><table border=0 cellpadding=0>")
        for field in self.table:
	    if field is None: continue
            val = self.__dict__[field]
            lines.append("<tr><td align=right>%s</td>"%field)
            lines.append("<td align=left><b>%s</b></td></tr>"%val)
        lines.append("</table></td></tr></table>")
        lines.append(self.description)
        lines.append("</td></tr></table><br>")

        return string.join(lines, os.linesep) + os.linesep
        
        



def loadprojects(dir):
    projs = []
    hunt = os.path.join(dir, '*.txt')
    for file in glob.glob(hunt):
        projs.append(Project(file))
    projs.sort(lambda x,y: cmp(x.name,y.name))
    return projs

def writeprojects(file, projects):
    for p in projects:
        file.write(p.fullhtml())



def miniproj(filename, projects):
    file = open(filename, 'w')
    p = projects[0]

    for p in projects:	
        if not p.date: continue
	prettyname = string.capitalize(p.name)
	prettydate = string.split(p.date, ',')[0]
	prettydate = string.split(prettydate)
	prettydate = prettydate[0][:3] + ' ' + prettydate[1]
        if p.image:
            file.write("""<p>
<a href=/gamelets/#%s><img src=/gamelets/%s
   border=1 width=100 height=75 alt=Latest></a><br>
""" % (p.name, p.image))
	file.write('<a href=/gamelets/#%s><b>%s</b></a><br><font size=-1>%s</font></p>\n' %
		(p.name, prettyname, prettydate))


def updateprojects():
    games = loadprojects('games')
    games.sort()
    games.reverse()
    template = open(PROJECTTEMPLATE)
    index = open(PROJECTINDEX, 'w')
    for line in template.readlines():
        strip = string.rstrip(line)
        if strip == '##GAMES##':
            writeprojects(index, games)
        else:
            index.write(line)

    all = games
    #all.sort()
    #all.reverse()
    newest = all[:2]
    print 'LATEST GAMELETS'
    for p in newest:
        print p.name, p.date
    miniproj('../minigamelets.html', newest)
	

updateprojects()
