#! /usr/bin/python

import sqlite3
from datetime import datetime
import sys

width = 96
days = ["S", "M", "T", "W", "T", "F", "S"]

def dayFraction(d):
	seconds = (d.hour * 3600 + d.minute * 60 + d.second)
	return seconds / (24.0 * 3600)

def printLine(day, line, total):
	if (day == None):
		return
	total = total * 24
	dayOfWeek = days[int(day.strftime("%w"))]
	dayString = day.strftime("%d-%b-%Y")
	print '{} {} {} {:>4.1f} {}'.format(day, dayOfWeek, line, total, longString(int(total), '#'))

def printHours():
	print '             ',
	for i in range(24):
		sys.stdout.write('{:<4}'.format(i))
	print

def longString(count, c = ' '):
	s = ''
	for i in range(count):
		s = s + c
	return s

conn = sqlite3.connect('BabyCare.db')
c = conn.cursor()

c.execute('select starttime, endtime from event_v2 where eventtype=1 order by starttime')

day = None
count = 0
line = bytearray(longString(width))
total = 0.0
while True:
	r = c.fetchone()
	if (r == None):
		break
	start = datetime.fromtimestamp(r[0] / 1000)
	end = datetime.fromtimestamp(r[1] / 1000)
	startFraction = dayFraction(start)
	endFraction = dayFraction(end)
	startPos = int(startFraction * width)
	endPos = int(endFraction * width)	
	if (start.date() != day):
		printLine(day, line, total)
		line = bytearray(longString(width))
		total = 0
		day = start.date()
		count = count + 1
		if (count % 10 == 0):
			printHours()

	line[startPos] = '+'

	if (end.date() != day):
		total = total + 1 - startFraction
		line[startPos + 1:width] = longString(width - startPos - 1, '#')
		startPos = -1
		printLine(day, line, total)
		line = bytearray(longString(width))
		total = endFraction
		day = end.date()
		count = count + 1
		if (count % 10 == 0):
			printHours()
	else:
		total = total + endFraction - startFraction
	
	line[endPos]= '@'
	if (endPos - startPos > 1):
		line[startPos + 1:endPos] = longString(endPos - startPos - 1, '#')
printLine(day, line, total)
