#!/usr/bin/env python

import os
import re
import sys
sys.path.insert(0, os.path.realpath(os.path.join(os.path.dirname(__file__), "..")))

import gtk
from Taskhelm import options
from Taskhelm.utils import (screen, debug)
from Taskhelm.utils.debug import dbg
from Taskhelm.browser.browser import TasksBrowser
from Taskhelm.taskwarrior import TaskWarrior

def load_config(filename):
    '''Converts config file contents into a dict

    Values for keys ending in 's' are converted into lists.
    yes/no is converted into True/False.
    '''
    config = {}
    if not os.path.exists(filename):
        return config

    re_pair = re.compile("^\s*([^=]+?)\s*=\s*(.*)$")

    file = open(filename, 'r')
    for line in file:
        m = re_pair.match(line)
        if m:
            key = m.group(1)
            value = m.group(2)

            if key[len(key)-1] == 's':
                # Split on commas, then strip excess whitespace
                value = [x.strip() for x in value.split(',')]
            elif value == 'yes':
                value = True
            elif value == 'no':
                value = False

            config[key] = value
    file.close()
    return config

def which(program):
    def is_exe(fpath):
        return os.path.exists(fpath) and os.access(fpath, os.X_OK)

    fpath, fname = os.path.split(program)
    if fpath:
        if is_exe(program):
            return program
    else:
        for path in os.environ["PATH"].split(os.pathsep):
            exe_file = os.path.join(path, program)
            if is_exe(exe_file):
                return exe_file

    return None

def is_first_time_user():
    dbg("is_first_time_user()")
    if os.path.exists(os.path.expanduser("~/.taskrc")):
        return False
    if os.path.exists(os.path.expanduser("~/.task/pending.data")):
        return False
    return True

def install_default_tasks():
    dbg("install_default_tasks()")
    dest = os.path.expanduser("~/.task")
    source = "/usr/local/share/taskhelm/initial_tasks"

    if not os.path.exists(source):
        source = os.path.realpath(os.path.join(os.path.dirname(__file__), "../data"))
        if not os.path.exists(source):
            sys.stdout.write("Error:  Could not find initial tasks\n")
            return False

    from shutil import (copytree, rmtree, move)
    try:
        dbg("Copying default tasks")
        if os.path.exists(dest):
            backup = "%s.bak" %(dest)
            rmtree(backup, ignore_errors=True)
            move(dest, backup)
        dbg("  %s -> %s" %(source, dest))
        copytree(source, dest)
        return True
    except:
        sys.stderr.write("Failed to copy %s to %s\n",
                         source, dest)
        raise
    return False

if __name__ == "__main__":
    opts = options.parse_commandline()

    debug.ENABLED = opts.debug
    filename = os.path.expanduser("~/.taskhelmrc")
    config = load_config(filename)

    # Verify our environment is set up properly
    if not which('task'):
        sys.stderr.write("Could not find 'task'.  Is TaskWarrior installed?\n")
        sys.exit(1)

    elif TaskWarrior.VERSION() not in TaskWarrior.SUPPORTED_VERSIONS:
        sys.stderr.write("Sorry, Taskhelm does not support the installed version of TaskWarrior\n")
        sys.stderr.write("   task-%s\n" %(TaskWarrior.VERSION()))
        sys.stderr.write("It works with these versions:\n")
        for version in TaskWarrior.SUPPORTED_VERSIONS:
            sys.stderr.write("  + task %s\n" %(version))
        sys.exit(1)

    elif not screen.X_is_running():
        sys.stderr.write("Could not open X display\n")
        sys.exit(1)

    # First time user... include the default tasks
    elif is_first_time_user():
        dbg("Installing default tasks")
        install_default_tasks()

    # Handle different invocation methods
    if opts.quick_entry:
        from Taskhelm.dialogs.task_add import NewTaskDialog
        dlg = NewTaskDialog()
        sys.exit(dlg.main())

    else:
        dbg("main:  Instantiating browser")
        browser = TasksBrowser(config=config)
        browser.debug = opts.debug
        dbg("main:  Starting program")
        gtk.main()
        dbg("main:  Ending program")

    sys.exit(0)

