#include <stdlib.h>
#include <string.h>
#include "tap.h"
#include "gif.h"

#define ID_GIF 0x80000104

TAP_ID( ID_GIF );
TAP_PROGRAM_NAME("GIF Show");
TAP_AUTHOR_NAME("TOPFIELD");
TAP_DESCRIPTION("It is sample tap program.");
TAP_ETCINFO(__DATE__);


typedef void (*FUNC)(void);
volatile int _exitFlag = 0;

int selectMode;
GIF gif;
TYPE_Window win;
int rgn;

word ShowGif( char *name )
{
	int i;
	int result = 0;
	word rgn = TAP_Osd_Create( 0, 0, 720, 576, 0, FALSE );
	LoadGifDirect( rgn, name );

	return rgn;
}

void ShowGifList( dword selNum )
{
	int totalEntry;
	TYPE_File file;

	rgn = TAP_Osd_Create( 0, 0, 720, 576, 0, FALSE );

	TAP_Win_SetDefaultColor( &win );
	TAP_Win_Create( &win, rgn, 100, 100, 200, 200, FALSE, TRUE );
	TAP_Win_SetTitle( &win, "GIF FILES", 0, FNT_Size_1622 );

	// find .gif files...
	totalEntry = TAP_Hdd_FindFirst( &file );
	while( totalEntry-- )
	{
		if( IsGif( file.name ) )
		{
			TAP_Win_AddItem( &win, file.name );
		}
		if( totalEntry==0 || TAP_Hdd_FindNext( &file ) == 0 )
		{
			break;
		}
	}

    TAP_Win_SetSelection( &win, selNum );
}


dword TAP_EventHandler( word event, dword param1, dword param2 )
{
    static word gifRgn;
	static int selNum, i;
	static char gifName[256];

    if( event != EVT_KEY )
        return param1;

	if( selectMode == 1 )
	{
		if( param1 == RKEY_Exit )
		{
			TAP_Win_Delete( &win );
            TAP_Osd_Delete( rgn );
			_exitFlag = 1;
		}
		else if( param1 == RKEY_Ok )
		{
			selNum = TAP_Win_GetSelection( &win );

			i = 0;
			while(1)
			{
				gifName[i] = win.item[selNum][i];
				if( gifName[i]==0 ) break;
				i++;
			}
			TAP_Win_Delete( &win );
            TAP_Osd_Delete( rgn );

			gifRgn = ShowGif( gifName );
			selectMode = 2;
		}
		else
		{
			TAP_Win_Action( &win, param1 );
		}
	}
	ef( selectMode == 2 )
	{
		if( param1 == RKEY_Exit || param1 == RKEY_Ok )
		{
        	TAP_Osd_Delete( gifRgn );
			selectMode = 1;
			ShowGifList( selNum );
		}
	}

	return 0;
}

bool IsGif( char *name )
{
    static char tmp[128];

    strcpy( tmp, name );
    strlwr( tmp );
    if( strcmp( tmp + strlen(tmp) - 4, ".gif" ) )
        return FALSE;
    else
        return TRUE;
}

int TAP_Main(void)
{
	ShowGifList( 0 );
    
	selectMode = 1;
	while(1)
	{
		TAP_SystemProc();
        if( _exitFlag ) 
        {
            break;
        }
	}

	return 0;
}


