#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# starenka @ Sep 24, 2008 2008 12:06:53 AM

import sqlite3
import os,sys
import string
import datetime,time
from optparse import OptionParser

usage = """\n\tmakam [-n "client|project|task|detail"] [-t] [-e] [-l]
\tmakam -n "Blba Julca|Deratizace|Shaneni pasticek|blablablabla"
\tmakam -t
\tmakam -l"""

parser = OptionParser(usage)
parser.add_option('-n','--new',action='store',dest='new',default = False,\
                  help='add new record')
parser.add_option('-t','--toggle',action='store_true',dest='toggle',default = False,\
                  help='toggles pause/resume current action')
parser.add_option('-l','--list',action='store_true',dest='list',default = False,\
                   help='list')
(options,args) = parser.parse_args()    

def seconds_to_human(seconds):
    hours = seconds / 3600 
    minutes = seconds / 60 % 60
    seconds = seconds % 60 
    return str(hours).rjust(2,'0')+':'+str(minutes).rjust(2,'0')+':'+str(seconds).rjust(2,'0')

home = os.path.expanduser("~")+'/'
now = str(time.time())[:-3]
file_stamp = datetime.datetime.now().strftime("%m-%Y")

conn = sqlite3.connect(home+'timesheet'+file_stamp)
c = conn.cursor()

try:
    c.execute('''CREATE TABLE sheet
(start INTEGER, end INTEGER, client TEXT, 
project TEXT, task TEXT, detail TEXT)''')
    print '\n(*): No worsheet available. Creating '+home+'timesheet'+file_stamp
except sqlite3.OperationalError, e:
    print '\n(*): '+file_stamp+' worksheet already exists. Hit me.'
conn.commit()

if options.new != False:
    data = options.new.split("|")
    if len(data)<4:
        for i in range(len(data),4):
            data.append('');
    c.execute('INSERT INTO sheet VALUES (?,?,?,?,?,?)',
              (str(time.time())[:-3],'0',data[0],data[1],data[2],data[3]))
    print '(*): Added!'
    conn.commit()
    c.close()

if options.list or (len(sys.argv) == 1):
    c.execute('SELECT * FROM sheet ORDER BY start DESC')
    for row in c:
        start = time.localtime(row[0])
        print str(start[2]).rjust(2,'0')+'.'+str(start[1]).rjust(2,'0')+\
        ' '+str(start[3]).rjust(2,'0')+':'+str(start[4]).rjust(2,'0')+\
        '\t'+row[2]+'\t'+row[3]+'\t'+row[4]+'\t'+row[5]
        if str(row[1]) != '0':
            end = time.localtime(row[1])
            print str(end[2]).rjust(2,'0')+'.'+str(end[1]).rjust(2,'0')+\
            ' '+str(end[3]).rjust(2,'0')+':'+str(end[4]).rjust(2,'0')+\
            '\t\t(*) task time: '+seconds_to_human(row[1]-row[0])
        else: print '\t\t\t(*) task in progress'

if options.toggle:
    c.execute('SELECT * FROM sheet ORDER BY start DESC LIMIT 1')
    for row in c:
        start = row[0]
        project = row[3]
        task = row[4]
        end = row[1]
    if str(end) == '0':
        c.execute('UPDATE sheet SET end = ? WHERE start = ?',(now,start))
        print '(*): "'+project+'/'+task+'" paused.\n\ttime elapsed: '+seconds_to_human(int(now)-int(start))
    else:
        row = list(row)
        row[0] = now
        row[1] = 0
        print '(*): "'+project+'/'+task+'" resumed!"'
        c.execute('INSERT INTO sheet VALUES (?,?,?,?,?,?)',row)
	conn.commit()
    c.close()        