#include "tap.h"

#define ID_CLOCK 0x80000103

TAP_ID( ID_CLOCK );
TAP_PROGRAM_NAME("Fire Clock");
TAP_AUTHOR_NAME("TOPFIELD");
TAP_DESCRIPTION("It is sample tap program.");
TAP_ETCINFO(__DATE__);

static int _exitFlag = 0;
static int _clockShow = 0;
static int _normalState = 0;
static dword rgn;

void DrawLine( byte rgn, int Ax, int Ay, int Bx, int By, int Color );

extern byte fireLut[256][4];

void Fire( byte *buffer, int xs, int ys );
void Fire2( byte *buffer, int xs, int ys );

int Fire2Power=127;

byte *scrBuf;

#define CLOCK_W  100
#define CLOCK_H   60

void DrawClock( int color )
{
	char str[10];

	word mjd; byte hour; byte min; byte sec;
	dword x2, y2;

	TAP_GetTime( &mjd, &hour, &min, &sec);

	TAP_SPrint( str, "%02d:%02d:%02d", hour, min, sec );
	TAP_Osd_DrawString1926( str, CLOCK_W, COLOR_Black, scrBuf+CLOCK_W*30, -1 );
	TAP_Osd_DrawString1926( str, CLOCK_W, color, scrBuf+CLOCK_W*29, -1 );
}

dword TAP_EventHandler( word event, dword param1, dword param2 )
{
    dword mainState, subState;

    if( event == EVT_IDLE )
    {
    	if( _clockShow==0 )
    		return;

    	DrawClock( 150+TAP_Sin( 50,TAP_GetTick() ) );
    	Fire( scrBuf, CLOCK_W, CLOCK_H );
    	DrawClock( 255 );
    	TAP_Osd_DrawPixmap( rgn, 0, 0, CLOCK_W, CLOCK_H, scrBuf, FALSE, OSD_256 );
        return 0;
    }

    if( event != EVT_KEY )
        return param1;
    
	TAP_GetState( &mainState, &subState );

    if( mainState != STATE_Normal )
    {
        if( mainState != STATE_Tap || subState != ID_CLOCK )
            return param1;
    }

    if( _clockShow )
    {
    	_clockShow = 0;
		TAP_Osd_Delete(rgn);
		TAP_EnterNormal();
        return param1;
    }

    if( mainState == STATE_Normal && param1 == RKEY_Sleep )
    {
   		_clockShow = 1;
        TAP_ExitNormal();
   		TAP_Osd_SetLut( 0, fireLut );
   		rgn = TAP_Osd_Create( 570, 450, CLOCK_W, CLOCK_H, 0, FALSE );
   		DrawClock( 250 );
       	return 0;	// Drop param1
    }
	return param1;
}

int TAP_Main(void)
{
	int i;

    scrBuf = (byte *)TAP_MemAlloc( CLOCK_W * CLOCK_H );
    memset( scrBuf, 0, CLOCK_W*CLOCK_H );

	return 1;
}


