//*****************************************************************************
//
//	Timer.m.  
//
//		by	Felipe A. Rodriguez		
//
//	This code is supplied "as is" the author makes no warranty as to its 
//	suitability for any purpose.  This code is free and may be distributed 
//	in accordance with the terms of the:
//		
//			GNU GENERAL PUBLIC LICENSE
//			Version 2, June 1991
//			copyright (C) 1989, 1991 Free Software Foundation, Inc.
// 			675 Mass Ave, Cambridge, MA 02139, USA
//
//*****************************************************************************

#import "Timer.h"
#import "Coordinator.h"

	// used in producing timed events
static DPSTimedEntry timerTimeTag;
static void time_func();



@implementation Timer

//*****************************************************************************
//
// 		called by DPS timed entry 
//
//*****************************************************************************
 
- timer:sender
{
	time(&ltime);						// Get time and place in time_t
	[self timerEngine:sender];
	
    return self;
}
//************************************************************************
//
// 		online timer engine
//
//************************************************************************
 
- timerEngine:sender
{
static int hour, min;
static char tmpbuf[32];
		
		// session
	ltime -= StartTime;							// time elapsed since start
	hour = (int)floor((ltime/60)/60);
	min = (int)floor(((((float)ltime/60.0)/60.0) - (float)hour) * 60.0);
	sprintf(tmpbuf, "%d:%02d", hour, min);
	[sessionView setStringValue:tmpbuf];		// session total
	if(delegate && sender)						// if we've been fired
		[delegate showMenuTimer:tmpbuf];
		// month
	mtime = ltime + savedTime;
	hour = (int)floor((mtime/60)/60);
	min = (int)floor(((((float)mtime/60.0)/60.0) - (float)hour) * 60.0);
	sprintf(tmpbuf, "%d:%02d", hour, min);
	[monthView setStringValue:tmpbuf];			// mo total
	
    return self;
}
//************************************************************************
//
//		 Fire timer 
//
//************************************************************************

- Fire:sender 
{
	[self initFromDDB];
    [self setDelegate:sender];		// he who fires us is our delegate
	time(&ltime);					// Get time and place in time_t
	StartTime = ltime;				// store start time
    if(!timerTimeTag)									
		timerTimeTag = DPSAddTimedEntry(		// register function time_func
			60.0, 								// to be called every period of 		
			(DPSTimedEntryProc)time_func, 		// arg0
			(id)self, 
			NX_BASETHRESHOLD);
	[self timerEngine:self];
	
    return self;
}
//************************************************************************
//
//		 Load timer nib
//
//************************************************************************

- showTimerPanel:sender 
{
time_t pmtime;
int hour, min;
static char tmpbuf[32];
		
    if(!timerPanel)
		[NXApp loadNibSection:"Timer.nib" owner:self withNames:NO];
	if(!delegate)						// if not fired	
		{
		[self initFromDDB];
		time(&ltime);					// Get time and place in time_t
		StartTime = ltime;				// store start time
		}
	[self timer:nil];

			// previous month
	pmtime = (time_t)atol(NXGetDefaultValue([NXApp appName], "preMonthTime"));
	hour = (int)floor((pmtime/60)/60);
	min = (int)floor(((((float)pmtime/60.0)/60.0) - (float)hour) * 60.0);
	sprintf(tmpbuf, "%d:%02d", hour, min);
	[previousMonthView setStringValue:tmpbuf];				// pre mo total

	[timerPanel setFrameUsingName:[timerPanel title]];		// remem loc/size
	[timerPanel setFrameAutosaveName:[timerPanel title]];	// remem loc/size
    [timerPanel makeKeyAndOrderFront:self];
	
    return self;
}
//*****************************************************************************
//
// 		stop the timer by removing the DPS timed entry 
//
//*****************************************************************************

- stopTimer
{
static char str[16];

    if (timerTimeTag)									// remove timed entry
         DPSRemoveTimedEntry (timerTimeTag);
    timerTimeTag = (DPSTimedEntry)0;
	if(delegate)										// if we've been fired
		{												// save added time used
		sprintf(str,"%ld", (long)mtime); 
		if(!NXWriteDefault([NXApp appName], "savedTime", str))
			[[NXApp delegate] showAlert:"ddbWriteError"];
		sprintf(str,"%ld", (long)monthTime); 		// save mo,yr of this ses'n
		if(!NXWriteDefault([NXApp appName], "monthTime", str))
			[[NXApp delegate] showAlert:"ddbWriteError"];
		}
	delegate = nil;										// signal not fired
		
    return self;
}
//*****************************************************************************
//
// 		designated initializer for timer 
//
//*****************************************************************************

- init 
{
	[super init];

    return 	[self initFromDDB];
}
- initFromDDB 
{
int mo, yr;
static char str[16];

    savedTime = (time_t)atol(NXGetDefaultValue([NXApp appName], "savedTime"));
    monthTime = (time_t)atol(NXGetDefaultValue([NXApp appName], "monthTime"));
	tmMonth = localtime(&monthTime);					// Convert time_t to tm
	mo = tmMonth->tm_mon;
	yr = tmMonth->tm_year;			// used because localtime doing weird thing
	time(&ltime);					// Get time and place in time_t
	timestamp = localtime(&ltime);						// Convert time_t to tm
	if((0 != (timestamp->tm_mon - mo)) || (0 != (timestamp->tm_year - yr)))
		{											// test for new mo,yr
		sprintf(str,"%ld", (long)savedTime); 		// save mo,yr as previous
		if(!NXWriteDefault([NXApp appName], "preMonthTime", str))
			[[NXApp delegate] showAlert:"ddbWriteError"];
		time(&monthTime);
		savedTime = 0;								// new mo or yr, reset
		}									
		
    return self;
}

- free 
{
    if(timerPanel)
	    [timerPanel close];
    [self stopTimer];
		
    return [super free];
}
//*****************************************************************************
//
// 		set a delegate while we are in fired state 
//
//*****************************************************************************

- setDelegate:anObject
{
    delegate = anObject;
	
    return self;
}

@end

//************************************************************************
//
//		This fucntion is registered by DPSaddtimedentry.
//		It is subsequently called every period t as registered  
//		in arg 0 of DPSaddtimedentry.
//
//************************************************************************

static void time_func(DPSTimedEntry time_tag, double now, id self)
{
	[self timer:self];
}
