#!/usr/bin/env python
# Anatol Ulrich, web@mail.taugt.net
# public domain

import csv
from collections import defaultdict

def passthru(col): return col
def get_filter(column):
    """ slower than necessary, because the dict gets reconstructed each call, but you know what? it's still fucking fast enough """
    def url(col): 
        if col == "todo": return "todo"
        return '<a href="%(col)s">%(col)s</a>' % {"col": col}
    def completion_status(col): return col + "%"
    def license(col): return col #todo: link to PAGES
    filters = defaultdict(lambda: passthru)
    filters["url"] = url
    filters["completion status"] = completion_status
    filters["license"] = license
    return filters[column]

def process_row(row, filters = None):
    elem = "td"
    if not filters:
        elem = "th"
        filters = [passthru] * len(row)
    return "<tr>" + "".join( process_col(col, f, elem) for col, f in zip(row, filters)) + "</tr>\n"

def process_col(col, filter, elem="td"):
    return "<%s>" % elem + filter(col) + "</%s>" % elem

def process_csv(filename):
    result = "<table>\n"
    reader = csv.reader(open(filename), delimiter="\t")
    header = reader.next()
    filters = [get_filter(col) for col in header]
    result += process_row(header)
    for row in reader:
        result += process_row(row, filters = filters)
    return result+"</table>"

index_html = open("index.html","w")
for chunk in open("index.html.template"):
    if chunk.endswith(".csv\n"):
        chunk = process_csv(chunk[:-1])
    index_html.write(chunk)

index_html.close()

