#!/usr/local/bin/python2.7
# -*- coding:utf-8 -*-

'''Command line user interface for manipulating tasks in gtg.

Copyright (C) 2010 Bryce W. Harrington

This program is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation; either version 2 of the License, or (at your
option) any later version.  See http://www.gnu.org/copyleft/gpl.html for
the full text of the license.
'''

import re
import sys
import os
import dbus
import cgi
import getopt
import textwrap
from datetime import datetime, date, timedelta
from string import split

def _(text):
    return text

def usage():
    f = "  %-30s %s\n"
    progname = sys.argv[0]

    text = _("gtcli -- a command line interface to gtg\n")
    text += "\n"

    text += _("Options:\n")
    text += f%( "-h, --help", _("This help") )
    text += "\n"

    text += _("Basic commands:\n")
    text += f%( "gtcli new", _("Create a new task") )
    text += f%( "gtcli show <tid>", _("Display detailed information on given task id") )
    text += f%( "gtcli edit <tid>", _("Opens the GUI editor for the given task id") )
    text += f%( "gtcli delete <tid>", _("Removes task identified by tid") )
    text += f%( "gtcli list [all|today|<filter>|<tag>]...", _("List tasks") )
    text += f%( "gtcli count [all|today|<filter>|<tag>]...", _("Number of tasks") )
    text += f%( "gtcli summary [all|today|<filter>|<tag>]...", _("Report how many tasks starting/due each day") )
    text += f%( "gtcli postpone <tid> <date>", _("Updates the start date of task") )
    text += f%( "gtcli close <tid>", _("Sets state of task identified by tid to closed") )
    text += f%( "gtcli browse [hide|show]", _("Hides or shows the task browser window"))

    text += "\n"
    text += "http://gtg.fritalk.com/\n"
    sys.stderr.write( text )

def die(code=1, err=None):
    if err:
        sys.stderr.write(str(err))
    sys.exit(code)

def connect_to_gtg():
    try:
        bus = dbus.SessionBus()
    except dbus.exceptions.DBusException, e:
        if "X11 initialization failed" in e.get_dbus_message():
            os.environ['DISPLAY'] = ":0"
            bus = dbus.SessionBus()
        else:
            print "dbus exception: '%s'" %(err)
            raise

    liste = bus.list_names()
    busname = "org.gnome.GTG"
    remote_object = bus.get_object(busname,"/org/gnome/GTG")
    return dbus.Interface(remote_object,dbus_interface="org.gnome.GTG")

def new_task(title, body):
    """ Retrieve task via dbus """
    timi = connect_to_gtg()
    timi.NewTask("Active", title, '', '', '', [], body, [])

def delete_task(tid):
    """ Remove a task via dbus """
    timi = connect_to_gtg()
    timi.DeleteTask(tid)

def close_task(tid):
    """ Marks a task closed """
    timi = connect_to_gtg()
    task_data = timi.GetTask(tid)
    task_data['status'] = "Done"
    timi.ModifyTask(tid, task_data)

def show_task(tid):
    """ Displays a given task """
    timi = connect_to_gtg()
    task_data = timi.GetTask(tid)
    content_regex = re.compile(r"<content>(.+)</content>", re.DOTALL)

    content = task_data['text'] + "\n(unknown)"
    m = content_regex.match(task_data['text'])
    if m:
        content = m.group(1)

    print task_data['title']
    if len(task_data['tags'])>0:
        print " %-12s %s" %('tags:', task_data['tags'][0])
    for k in ['id', 'startdate', 'duedate', 'status']:
        print " %-12s %s" %(k+":", task_data[k])
    if len(task_data['parents'])>0:
        print " %-12s %s" %('parents:', task_data['parents'][0])
    print
    print content

def postpone(identifier, startdate):
    """ Change the start date of a task """
    timi = connect_to_gtg()
    
    tasks = []
    if identifier[0] == '@':
        filters = _criteria_to_filters(identifier)
        filters.extend(['active','workview'])
        timi = connect_to_gtg()
        tasks = timi.GetTasksFiltered(filters)
    else:
        tasks = [ timi.GeTask(identifier) ]

    for task in tasks:
        task['startdate'] = startdate
        print "%-12s %-20s %s" %(task['id'], ", ".join(task['tags']), task['title'])
        timi.ModifyTask(task['id'], task)

def open_task_editor(tid):
    """ Load task in the task editor gui """
    timi = connect_to_gtg()
    task_data = timi.OpenTaskEditor(tid)

def toggle_browser_visibility(state):
    """ Cause the task browser to be displayed """
    timi = connect_to_gtg()
    if state == "hide":
        timi.HideTaskBrowser()
    elif state == "minimize" or state == "iconify":
        if not timi.IsTaskBrowserVisible():
            timi.ShowTaskBrowser()
        timi.IconifyTaskBrowser()
    else:
        timi.ShowTaskBrowser()

def _criteria_to_filters(criteria):
    if not criteria:
        filters = ['active']
    else:
        filters = split(criteria, ' ')
    
    # Special case 'today' filter
    if 'today' in filters:
        filters.extend(['active', 'workview'])
        filters.remove('today')
    return filters

def count_tasks(criteria):
    """ Print a simple count of tasks matching criteria """

    filters = _criteria_to_filters(criteria)
    timi = connect_to_gtg()
    tasks = timi.GetTasksFiltered(filters)

    total = 0
    for task in tasks:
        if 'title' not in task:
            continue
        total += 1

    print total
    return total

def summary_of_tasks(criteria):
    """ Print report showing number of tasks starting and due each day """

    if not criteria:
        criteria = 'workable'

    filters = _criteria_to_filters(criteria)
    filters.append('active')
    timi = connect_to_gtg()
    tasks = timi.GetTasksFiltered(filters)

    report = { }
    for t in tasks:
        if not t['startdate']:
            startdate = 'unscheduled'
        elif datetime.strptime(t['startdate'], "%Y-%m-%d") < datetime.today():
            startdate = date.today().strftime("%Y-%m-%d")
        else:
            startdate = t['startdate']

        if startdate not in report:
            report[startdate] = { 'starting':0, 'due':0 }
        report[startdate]['starting'] += 1

        duedate = t['duedate'] or 'never'
        if duedate not in report:
            report[duedate] = { 'starting':0, 'due':0 }
        report[duedate]['due'] += 1

    day = date.today()
    print "%-20s %5s %5s" %("", "Start", "Due")
    if report.has_key('unscheduled'):
        print "%-20s %5d %5d" %('unscheduled', 
                                report['unscheduled']['starting'],
                                report['unscheduled']['due'])
    num_days = 22
    fmt = "%a  %-m-%-d"
    if criteria and 'today' in criteria:
        num_days = 1
    for i in range(0, num_days):
        d = day + timedelta(i)
        dstr = str(d)
        if dstr in report:
            print "%-20s %5d %5d" %(d.strftime(fmt),
                                    report[dstr]['starting'],
                                    report[dstr]['due'])
        else:
            print "%-20s %5d %5d" %(d.strftime(fmt), 0, 0)
            

def list_tasks(criteria, count_only=False):
    """ Display a listing of tasks 
    
    Accepts any filter or combination of filters or tags to limit the
    set of tasks shown.  If multiple tags specified, it lists only tasks
    that have all the tags.  If no filters or tags are specified,
    defaults to showing all active tasks.
    """

    filters = _criteria_to_filters(criteria)
    timi = connect_to_gtg()
    tasks = timi.GetTasksFiltered(filters)

    tasks_tree = { }
    notag = '@__notag'
    for task in tasks:
        if 'title' not in task:
            continue
        if not task['tags'] or len(task['tags']) == 0:
            if notag not in tasks_tree:
                tasks_tree[notag] = []
            tasks_tree[notag].append(task)
        else:
            tags = []
            for tag in list(task['tags']):
                tags.append(tag)
                if tag not in tasks_tree:
                    tasks_tree[tag] = []
                tasks_tree[tag].append(task)

    # If any tags were specified, use only those as the categories
    keys = [t for t in filters if t[0]=='@']
    if not keys:
        keys = tasks_tree.keys()
        keys.sort()

    for key in keys:
        if key not in tasks_tree:
            continue
        if key != notag:
            print "%s:" %(key[1:])
        for task in tasks_tree[key]:
            text = textwrap.fill(task['title'], 
                                 initial_indent='',
                                 subsequent_indent=' ' * 40)
            print "  %-36s  %s" %(task['id'], text)

if __name__ == '__main__':
    try:
        opts, args = getopt.gnu_getopt(sys.argv[1:], "h", ["help"])
    except getopt.GetoptError, err:
        sys.stderr.write("Error: " + str(err) + "\n\n")
        usage()
        sys.exit(2)
    for o, a in opts:
        if o in ("-h", "--help"):
            usage()
            sys.exit(0)
        else:
            assert False, "unhandled option"

    if len(args) < 1:
        usage()
        sys.exit(2)

    command = args[0]

    if command == "new" or command == "add":
        subject_regex = re.compile("^Subject: (.*)$", re.M | re.I)

        title = " ".join(args[1:])
        body = sys.stdin.read()
        if subject_regex.search(body):
            subject = subject_regex.findall(body)[0]
            title = title + ": " + subject

        new_task(title, cgi.escape(body))

    elif command == "list":
        criteria = None
        if len(args)>1:
            criteria = ' '.join(args[1:])
        list_tasks(criteria, False)

    elif command == "count":
        criteria = None
        if len(args)>1:
            criteria = ' '.join(args[1:])
        count_tasks(criteria)

    elif command == "summary":
        criteria = None
        if len(args)>1:
            criteria = ' '.join(args[1:])
        summary_of_tasks(criteria)

    elif command == "rm" or command == "delete":
        if len(args)<2:
            usage()
            sys.exit(1)
        for tid in args[1:]:
            delete_task(tid)

    elif command == "close":
        if len(args)<2:
            usage()
            sys.exit(1)
        for tid in args[1:]:
            close_task(tid)

    elif command == "postpone":
        if len(args)<3:
            usage()
            sys.exit(1)
        postpone(args[1], args[2])

    elif command == "show":
        if len(args)<2:
            usage()
            sys.exit(1)
        for tid in args[1:]:
            show_task(tid)

    elif command == "edit":
        if len(args)<2:
            usage()
            sys.exit(1)
        for tid in args[1:]:
            open_task_editor(tid)

    elif command == "browse":
        state = None
        if len(args)>1:
            state = args[1]
        toggle_browser_visibility(state)

    else:
        die("Unknown command '%s'\n" %(command))


