#!/usr/bin/env python
# -*- coding: utf-8 -*- vim:sw=4:sts=4:et:ai:si:sta:fenc=utf-8

"""%(name)s: Fonction à usage de TODO pour gérer les tiddlywikis
USAGE
    %(name)s tiddlywiki.html [actions]
"""

try: True, False
except NameError: True, False = 1, 0

import os, sys, re
from os import path
from time import localtime

from base import *
from TiddlyWiki import *
from TiddlyWiki import ARGS_ENCODING # XXX
from TODO import *

######################################################################
# Fonctions de support pour TODO

def do_update_todo(twfile, project=None, id=None, todoline=None, args=None):
    """USAGE: update_todo project id todoline
    """
    i = 0
    if project is None:
        if args[i:i + 1]: project = args[i]
        if project is None: die("Il faut spécifier le projet")
        i = i + 1
    if id is None:
        if args[i:i + 1]: id = args[i]
        if project is None: die("Il faut spécifier l'id")
        i = i + 1
    if todoline is None:
        if args[i:i + 1]: todoline = unicode(args[i], ARGS_ENCODING)
        if todoline is None: die("Il faut spécifier la ligne de TODO")

    todofile = TiddlyTODOFile(twfile, project)
    if todoline:
        todo = TODO(todoline=todoline)
        todofile.put(todo)
    else:
        todofile.remove(id)
    todofile.save()

def do_report(todorc, **ignored):
    """USAGE: report
    """
    ts = TODOs(todorc)
    ts.do_report()

######################################################################
# L'application principale

def ensure(twfile):
    if twfile is None: twfile = "TODO.html"
    if not path.exists(twfile): die("Fichier inexistant: %s" % twfile)
    else: return twfile

def run():
    todorc = None
    twfile = None

    opts, args = get_args(None, [
        ("h", "help", "Afficher l'aide"),
        ("c:", None, "Spécifier le fichier todorc"),
        ("f:", None, "Spécifier le fichier tiddlywiki.html"),
        ])

    for opt, value in opts:
        if opt in ("-h", "--help"):
            print __doc__ % {"name": path.split(sys.argv[0])}
            sys.exit(0)
        elif opt in ("-c", ):
            todorc = value
        elif opt in ("-f", ):
            twfile = value

    action = args[0:1] and args[0] or "list"
    if action in ("l", "list"):
        list_tiddlers(ensure(twfile), args[1:])
    elif action in ('a', 'add', 'r', 'replace'):
        replace_tiddler(ensure(twfile), args=args[1:])
    elif action in ('d', 'delete'):
        delete_tiddler(ensure(twfile), args=args[1:])
    elif action in ('update_todo', 'update_done'):
        do_update_todo(ensure(twfile), args=args[1:])
    elif action in ('report', ):
        do_report(todorc, args=args[1:])
    elif action in ('update_all', ):
        # XXX à faire: équivalent de TODO update
        do_update_all(todorc, args=args[1:])
    else:
        die("Action invalide: %s" % action)

if __name__ == "__main__":
    run()
