
// ****************************************************************************
//
//                           Page TIM - Timer
//
// ****************************************************************************

#include "../include.h"

Bool TimIsPause = False;	// pause timer
u32 TimStart;			// start time in [ms]
u32 TimPause;			// pause time in [ms]
u32 TimHold;			// hold time in [ms]

// TIM initialize
void TIM_Init()
{
	// get start time
	TimStart = SysTime;
}

// draw one value
void TIM_DispVal(u32 val, int y)
{
	// separate values
	u32 sec = val/1000;
	int ms = val - sec*1000;
	u32 min = sec/60;
	sec -= min*60;
	u32 h = min/60;
	min -= h*60;

	// overflow
	if (h > 99)
	{
		h = 99;
		min = 59;
		sec = 59;
		ms = 999;
	}

	// hours
	u8* s = DecNumBuf;
	int i = h/10;
	*s++ = i + '0';
	h -= i*10;
	*s++ = h + '0';
	*s++ = ':';

	// minutes
	i = min/10;
	*s++ = i + '0';
	min -= i*10;
	*s++ = min + '0';
	*s++ = ':';

	// seconds
	i = sec/10;
	*s++ = i + '0';
	sec -= i*10;
	*s++ = sec + '0';
	*s++ = '.';

	// milliseconds
	i = ms/100;
	*s++ = i + '0';
	ms -= i*100;
	i = ms/10;
	*s++ = i + '0';
	*s = 0;

	// clear row
	DrawRectClrFast(0, y, WIDTH, FONTH2);

	//    59:59.99
	// 99:59:59.99
	if (val <= 59*60*1000 + 59*1000 + 999)
	{
		DrawText2(DecNumBuf + 3, (WIDTH-8*16)/2, y);
	}
	else
	{
		DrawText(DecNumBuf, (WIDTH-11*8)/2, y+6);
	}
}

// display current counter value
void TIM_Disp()
{
	// select font 8x12
	SelFont12();

	// display values
	if (TimIsPause)
		TIM_DispVal(TimPause, ROW1_Y);
	else
		TIM_DispVal(SysTime - TimStart, ROW1_Y);
	TIM_DispVal(TimHold, ROW3_Y);

	// display update
	DispUpdate();
}

// Page TIM (returns key PREV/NEXT)
u8 PageTIM()
{
	u8 key;

	while (True)
	{
		// reload watchdog counter
		IWDG_Reload();

		// display current timer value
		TIM_Disp();

		// keyboard input
		key = KeyGet();
		switch (key)
		{
		// Prev
		case KEY_PREV:
		// Next
		case KEY_NEXT:
			return key;

		// Fast - pause
		case KEY_FAST:
			TimIsPause = !TimIsPause;
			TimPause = SysTime - TimStart;
			break;

		// Slow - hold
		case KEY_SLOW:
			TimHold = SysTime - TimStart;
			break;

		// Hold - reset
		case KEY_HOLD:
			TimStart = SysTime;
			TimPause = 0;
			TimHold = 0;
			TimIsPause = False;
			break;
		}
	}
}
