#!/usr/bin/env python
# This script is in the Public Domain. Author is Danny Milosavljevic <danny@scratchpost.org>

# TODO visibility (acls, ...)
# TODO day of week
# TODO also show appointments that should be running RIGHT NOW ;-)

import os
import sys
import time
import codecs
import exceptions
import errno

os.chdir(os.path.expanduser("~/info/dates"))

today = time.strftime("%Y-%m-%dT%H:%M")

print "%s_Today_Now" % today

entries = os.listdir(".")
entries.sort()

future_entries = [entry_key for entry_key in entries if entry_key >= today and not entry_key.startswith(".")]

def get_value(entry_key, sub_key, replacement = None):
	try:
		value = codecs.open(os.path.join(entry_key, sub_key), "r", "UTF-8").read()
	except exceptions.IOError, e:
		if e.errno == errno.ENOENT:
			return replacement
		else:
			raise
	return value

def get_flag(entry_key, sub_key):
	return os.path.exists(os.path.join(entry_key, sub_key))

def nvl(a, b):
	if a is None:
		return b
	else:
		return a

def print_short_overview(entry_key):
	i = entry_key.find(" ")
	j = entry_key.find("_")
	if j > -1 and j < i: # take the smaller one
		i = j

	if i > -1: # found
		date_part = entry_key[: i]
		topic_part = date_part[i: ]
	else:
		date_part = entry_key
		topic_part = ""

	beginning = get_value(entry_key, "beginning")
	ending = get_value(entry_key, "ending")
	location = get_value(entry_key, "location")
	#over = get_flag(entry_key, "over?")
	live = get_flag(entry_key, "live?")
	#topic = get_value(entry_key, "topic", topic_part)

	print "%s [%s .. %s]" % (date_part, nvl(beginning, ""), nvl(ending, ""))

for entry_key in future_entries:
	# keys:
	#    beginning
	#    end
	#    topic
	#    location
	#    attendees/
	##    over?
	#    live? ( not cancelled? )
	#    blurb
	#    
	#    
	#    

	print_short_overview(entry_key)

