
#import "TimerController.h"
#import "TimerListener.h"
#import "ClockView.h"
#import "sys/time.h"
#import <soundkit/Sound.h>

@implementation TimerController

- resetUnits {

	struct timeval 	tp;
	struct timezone tzp;
	
	gettimeofday(&tp,&tzp);
	
	lastUnitStart = tp.tv_sec;
	
	[clockView setValue:1.0];
	[units setIntValue:1];
 
    	return self;
}

- resetUnits:sender {

	return [self resetUnits];
}

static void stepClock(DPSTimedEntry teNumber,double now,void *userData) {
	
	TimerController	*self = (TimerController*)userData;
	struct timeval 	tp;
	struct timezone tzp;
	struct tm	*aTm;
	int		taktLen;
	
	gettimeofday(&tp,&tzp);
	
	aTm = localtime(&(tp.tv_sec));
	
	if( (aTm->tm_wday==6||aTm->tm_wday==0)&&![self->feierTag state] )
		[self->feierTag setState:YES];
		
	if( [self->feierTag state]||aTm->tm_hour>=18||aTm->tm_hour<8 )
		taktLen = 12;
	else
		taktLen = 6;
	
	if( taktLen!=[self->takt intValue] )
		[self->takt setIntValue:taktLen];
	
	taktLen *= 60;
	
	if( self->lastUnitStart+taktLen<=tp.tv_sec ) {
	
		//	Neue Einheit
		
		[self->units setIntValue:[self->units intValue]+1];
		
		self->lastUnitStart += taktLen;
		[[Sound findSoundFor:"Bonk"] play];
	}

	{
		float	aVal = (float)(self->lastUnitStart+taktLen
					-tp.tv_sec)/taktLen;
					
		[self->clockView setValue:aVal];
		 
		if( self->lastUnitStart+taktLen-tp.tv_sec<20 )
			[[Sound findSoundFor:"Tink"] play];
	}
}

- exit {

	[NXApp terminate:self];
	
	return self;
}

- init {

	struct timeval 	tp;
	struct timezone tzp;
	
	gettimeofday(&tp,&tzp);
	
	lastUnitStart = tp.tv_sec;
	
	DPSAddTimedEntry(1.0,stepClock,(void *)self,NX_BASETHRESHOLD);

	return self;
}

- appWillInit:sender {

	[NXApp setAppListener:[[TimerListener new] init]];
	
	return self;
}

@end
