#$Id: psionAgenda.py,v 1.1 1996/09/23 04:25:14 connolly Exp $
#

from struct import unpack, calcsize
from time import localtime, gmtime, asctime, ctime
import psionData
from psionData import readStruct, readQstr, debug

class T(psionData.DBF):
    def factory(self, ty):
	if ty == 1:
	    return TimedDayEntry
	elif ty == 2:
	    return UntimedDayEntry
	elif ty == 4:
	    return ToDoEntry
	return psionData.Record


class Entry(psionData.Record):
    def __init__(self, parent, ty, siz):
	self.siz = siz

    def loadAttrs(self, stream, attrs):
	if attrs & (1<<3) == 0: # alarm follows...
	    (alarmTime, qty) = readStruct('hb', stream)
	    alarmSound = stream.read(8)[:qty]

	    debug('alarm', alarmTime, alarmSound)

	if attrs & (1<<4) == 0:
	    (memoQty, ) = readStruct('h', stream)
	    stream.read(memoQty) #who knows what's in it!

	    debug('memo. len:', memoQty)

class TimedDayEntry(Entry):

#Type 1 (timed day entry):
#  Offset  0 (word): day number of the entry
#  Offset  2 (word): time of entry, in minutes past midnight
#  Offset  4 (byte): attributes (see below)
#  Offset  5 (byte): symbol in year view (0 to 31 mean do not show)
#  Offset  6 (word): length in minutes
#  Offset  8 (byte): text style (see below)
#  Offset  9 (qstr): text

    fmt = 'hhbchb'
    fmtQty = calcsize(fmt)

    def load(self, stream):
	(dayNum, time, attrs, yearSym, duration, sty) = \
		 unpack(self.fmt, stream.read(self.fmtQty))

	text = readQstr(stream)

	debug('timed day entry', asctime(gmtime(d2s(dayNum) + time)), attrs, 
	      yearSym, duration, sty, text)

	self.loadAttrs(stream, attrs)

class UntimedDayEntry(Entry):

    fmt = 'hhbcb'
    fmtQty = calcsize(fmt)

    def load(self, stream):
	(dayNum, time, attrs, yearSym, sty) = \
		 unpack(self.fmt, stream.read(self.fmtQty))

	text = readQstr(stream)

	debug('untimed day entry', asctime(gmtime(d2s(dayNum) + time)), attrs, 
	      yearSym, sty, text)

	self.loadAttrs(stream, attrs)

class ToDoEntry(Entry):
    fmt = 'hhbchbb'
    fmtQty = calcsize(fmt)

    def load(self, stream):
	(dayNum, time, attrs, yearSym, doneBy, listIndex, priDataFmt) =\
		 readStruct(self.fmt, stream)

	# watch out for alignment...
	(posn, style) = readStruct('ib', stream)
	text = readQstr(stream)

	debug('todo entry', asctime(gmtime(d2s(dayNum) + time)), attrs, 
	      yearSym, ctime(d2s(doneBy)), listIndex, priDataFmt, posn,
	      style, text)
	
	self.loadAttrs(stream, attrs)

# Utilities

def d2s(daynum):
    # assume 1970 bias in both systems
    return 60*60*24*daynum

def test():
    import sys

    a = T()
    a.load(sys.stdin)

if __name__ == '__main__': test()
