#!/usr/bin/env python
# -*- coding: latin-1 -*-

#
# This code is put in the public domain by Niclas Södergård
#
# How to use
# 1. Create a project file that looks like this
#    !Taxes
#    @Home Find all paperwork
#    @Call Call my accountant 123456
#    !Car repair
#    @Home Vacuum car
#    @Home Find summer tires
#    @Call Call workshop
#
# 2. Run gtd.py with an output directory as well as the project file as
#    arguments
#
# 3. It will now generate one text file per context given in the project
#    file. It will only take one entry per context per project. So if you
#    have multiple @Home contexts for the car repair only the first one
#    will be recorded (in style with GTD)
#

import sys

if len(sys.argv) < 3:
	print "Usage: gtd.py <destination directory> <project file>"
	sys.exit(1)
	
f = open(sys.argv[2])

contexts = {}
currentProject = "None"
lineCounter = 0
stopProject = 0

for line in f.readlines():
	lineCounter += 1
	
	# remove all blanks from the beginning and the end
	line = line.lstrip()
	line = line.rstrip()

	# if it is an empty line we skip it
	if len(line) == 0:
		continue
		
	if line[0] == "#":
		# comment, skip that line
		continue
	elif line[0] == "!":
		# new project, reset contexts
		currentProject = line[1:]
		stopProject = 0
	elif line[0] == "@":
		# new NA for the current project
		if stopProject == 1:
			continue
		
		context, action = line[1:].split(" ", 1)
#		if (currentProject != "None") and (context in seenContexts):
#			# we have seen this context before for this specific project
#			# so we ignore this NA
#			continue
		
#		seenContexts.append(context)
		if not contexts.has_key(context):
			contexts[context] ={}

		contexts[context][action] = currentProject
	elif line[0] == "*":
		# we will stop processing this project now
		stopProject = 1
	else:
		print "Unknown starting symbol on line %d." % lineCounter
		sys.exit(1)

f.close()

for c in contexts.keys():
	f = open("%s/%s.txt" % (sys.argv[1], c), "w")
	currentContext = contexts[c]
	f.write("@%s\n" % c)
	
	for action in currentContext.keys():
		f.write("\t - %s (%s)\n" % (action, currentContext[action]))
	
	f.close()

print contexts
