#include <exec/types.h>
#include <exec/memory.h>

#include <intuition/intuition.h>
#include <intuition/screens.h>

#include <libraries/gadtools.h>

#include <clib/exec_protos.h>
#include <clib/intuition_protos.h>
#include <clib/gadtools_protos.h>

#include "Fade.h"
#include "Fade_rev.h"
#include "/main.h"
#include "//defs.h"

struct fPrefObject
{
	LONG Delay;
	LONG Percent;
	LONG TopScr;
};

struct fPrefObject nP;
VOID *OldPrefs = 0L;
STATIC const UBYTE VersTag[] = VERSTAG;

int BT_SAVEClicked( VOID )
{
	if( OldPrefs )
	{
		CopyMem( &nP, OldPrefs, sizeof( struct fPrefObject ));
		SavePrefs( OldPrefs );
		OldPrefs = 0L;
	}
	
	return QUIT;
}

int BT_TESTClicked( VOID )
{
	MessageServer( BM_SENDBLANK );

	return OK;
}

int BT_CANCELClicked( VOID )
{
	OldPrefs = 0L;
	
	return QUIT;
}

int SL_DELAYClicked( VOID )
{
	nP.Delay = FadeMsg.Code;
	
	return OK;
}

int SL_PERCENTClicked( VOID )
{
	nP.Percent = FadeMsg.Code;
	
	return OK;
}

int CY_TOPSCRClicked( VOID )
{
	nP.TopScr = FadeMsg.Code;

	return OK;
}

#define BL_SetGadgetAttrs( Gad, Tag, Val ) GT_SetGadgetAttrs( FadeGadgets[Gad], FadeWnd, 0L, Tag, Val, TAG_END )

int FadeVanillaKey( VOID )
{
	switch( FadeMsg.Code ) {
	case 's':
		return BT_SAVEClicked();
	case 't':
		return BT_TESTClicked();
	case 'c':
		return QUIT;
	case 'd':
		BL_SetGadgetAttrs( GD_SL_DELAY, GTSL_Level, Inc( nP.Delay, 1, 59 ));
		return OK;
	case 'D':
		BL_SetGadgetAttrs( GD_SL_DELAY, GTSL_Level, Dec( nP.Delay, 1, 0 ));
		return OK;
	case 'p':
		BL_SetGadgetAttrs( GD_SL_PERCENT, GTSL_Level,
						  Inc( nP.Percent, 1, 100 ));
		return OK;
	case 'P':
		BL_SetGadgetAttrs( GD_SL_PERCENT, GTSL_Level,
						  Dec( nP.Percent, 1, 10 ));
		return OK;
	default:
		return OK;
	}
}

VOID DoPrefs( LONG command, VOID *Prefs )
{
	switch( command )
	{
	case STARTUP:
		OldPrefs = Prefs;
		CopyMem( Prefs, &nP, sizeof( struct fPrefObject ));
		if( !SetupScreen())
		{
			FadeLeft = ( Scr->Width - ComputeX( FadeWidth ))/2;
			FadeTop = ( Scr->Height - ComputeY( FadeHeight ) -
					   Font->ta_YSize )/2;
			if( !OpenFadeWindow())
			{
				BL_SetGadgetAttrs( GD_SL_DELAY, GTSL_Level, nP.Delay );
				BL_SetGadgetAttrs( GD_SL_PERCENT, GTSL_Level, nP.Percent );
				BL_SetGadgetAttrs( GD_CY_TOPSCR, GTCY_Active, nP.TopScr );
			}
			CloseDownScreen();
		}
		break;
	case IDCMP:
		if( HandleFadeIDCMP() != QUIT )
			break;
	case KILL:
		CloseFadeWindow();
		break;
	}
}

LONG WndSignal( VOID )
{
	return FadeWnd ? 1L << FadeWnd->UserPort->mp_SigBit : 0L;
}

VOID FillDefaults( VOID *Prefs )
{
	struct fPrefObject fPO = { 4L, 75L, 0L };

	CopyMem( &fPO, Prefs, sizeof( struct fPrefObject ));
}
