#!/bin/env python
import jppy
import getopt
import mx.DateTime
import sys
import string
import types

def usage():
    print """
jp_add_todo [options] todo_description
-n --note     [note string]     Set note field contents
-d --due      [date text]       Set the date, can be free-form text
-r --relative [days to go]      Set the date by saying how many days into the future it should be
-c --category [category]        Set the category (range 0-15, default 0, or String matching a current category)
-p --priority [pri number]      Range 1-5 (default 3)
"""

if len(sys.argv) == 1 :
    usage()
    sys.exit(2)
    
try:
    opts, args = getopt.getopt(sys.argv[1:], "hn:d:p:r:c:",
                               ["help","note=","due=","priority=","relative=","category="])
except getopt.GetoptError:
    print "Arguments could not be understood..."
    usage()
    sys.exit(2)

database = "ToDoDB"

tasklist = jppy.taskList()

todo = jppy.Todo()
todo['priority'] = 3 # set default explicity
todo.category = 0 # set default explicity

for o, a in opts:
    if o in ("-h", "--help"):
        usage()
        sys.exit()
    if o in ("-d", "--due"):
        todo['due'] = mx.DateTime.DateFrom(a)
    if o in ("-r", "--relative"):
        try:
            todo['due'] = mx.DateTime.now() + mx.DateTime.RelativeDate(days=int(a))
        except:
            print "Failed to set date to %s says into the future" % a
            sys.exit(2)                        
    if o in ("-p", "--priority"):
        try:
            assert(int(a) > 0)
            assert(int(a) < 6)
        except:
            print "Priority must be an integer in the range 1-5"
            sys.exit(2)            
        todo['priority'] = int(a)
    if o in ("-c", "--category"):
        try:
            a = int(a)
        except:
            pass
        if type(a) == types.IntType:
            try:
                assert(a >= 0)
                assert(a <= 15)
            except:
                print "Category must be an integer in the range 0-15, or a String"
                sys.exit(2)            
            todo.category = a
        else:
            cats = taskList.getCategories()
            if a in cats:
                todo.category = cats.index(a)
            else:
                print "Category must be an integer in the range 0-15, or a String matching one of %s" % repr(cats)
                sys.exit(2)

if not args:
    print "Todo description is required"
    sys.exit(2)              
todo['description'] = string.join(args)
tasklist.save(todo)

print todo
