#!/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._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.site = None
        self.version = 'Unknown'
        self.author = 'Unknown'
        self.status = 'Unknown'
	self.date = None
        self.description = 'No Description'
        self.table = 'author', 'version', 'date'  #, 'status'


    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, '=', 1)
                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):
        if not self.site:
            return str
        return "<a href=%s>%s</a>" % (self.site, 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(self._wrapinurl("<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._wrapinurl(self.name))
        lines.append("</b></font><br><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')

    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=/projects/#%s><img src=/projects/%s
   border=1 width=100 height=75 alt=Latest></a><br>
""" % (p.name, p.image))
	file.write('<a href=/projects/#%s><b>%s</b></a><br>%s - <font size=-1>%s</font></p>\n' %
		(p.name, prettyname, p.version, prettydate))


def updateprojects():
    games = loadprojects('games')
    apps = loadprojects('apps')
    libs = loadprojects('libs')
    dev = loadprojects('dev')
    grave = loadprojects('grave')
    template = open(PROJECTTEMPLATE)
    index = open(PROJECTINDEX, 'w')
    for line in template.readlines():
        strip = string.rstrip(line)
        if strip == '##GAMES##':
            writeprojects(index, games)
        elif strip == '##LIBS##':
            writeprojects(index, libs)
        elif strip == '##APPS##':
            writeprojects(index, apps)
        elif strip == '##DEV##':
            writeprojects(index, dev)
        elif strip == '##GRAVE##':
            writeprojects(index, grave)
        else:
            index.write(line)

    all = games+apps+libs+dev
    all.sort()
    all.reverse()
    newest = all[:4]
    print 'LATEST PROJECTS'
    for p in newest:
        print p.name, p.date
    miniproj('../miniproj.html', newest)
	

updateprojects()
