/*===========================================================================

FILE: pong.c
===========================================================================*/


/*===============================================================================
INCLUDES AND VARIABLE DEFINITIONS
=============================================================================== */
#include "AEEModGen.h"          // Module interface definitions
#include "AEEAppGen.h"          // Applet interface definitions
#include "AEEShell.h"           // Shell interface definitions

#include "AEESound.h"			// Sound Interface definitions

#include "pong.bid"
#include "pong.brh"

#define SIM_CLOCK 33 // 33 ms so aprox. 30 fps

const char* fRes = "pong.bar";

/*-------------------------------------------------------------------
Applet structure. All variables in here are reference via "pMe->"
-------------------------------------------------------------------*/
// create an applet structure that's passed around. All variables in
// here will be able to be referenced as static.
typedef struct _pong {
	AEEApplet      a ;	       // First element of this structure must be AEEApplet
   AEEDeviceInfo  DeviceInfo; // always have access to the hardware device information
   IDisplay      *pIDisplay;  // give a standard way to access the Display interface
   IShell        *pIShell;    // give a standard way to access the Shell interface

   AEEImageInfo pdlInf;
   AEEImageInfo balInf;
   IImage *pPaddle;
   IImage *pBall;
   AEERect pdlRect;
   AEERect balRect;

   int vBalX;
   int vBalY;

} pong;

/*-------------------------------------------------------------------
Function Prototypes
-------------------------------------------------------------------*/
static  boolean pong_HandleEvent(pong* pMe, AEEEvent eCode, uint16 wParam, uint32 dwParam);
boolean pong_InitAppData(pong* pMe);
void    pong_FreeAppData(pong* pMe);
void    sim(pong* pMe);

/*===============================================================================
FUNCTION DEFINITIONS
=============================================================================== */

/*===========================================================================
FUNCTION: AEEClsCreateInstance

DESCRIPTION
	This function is invoked while the app is being loaded. All Modules must provide this 
	function. Ensure to retain the same name and parameters for this function.
	In here, the module must verify the ClassID and then invoke the AEEApplet_New() function
	that has been provided in AEEAppGen.c. 

   After invoking AEEApplet_New(), this function can do app specific initialization. In this
   example, a generic structure is provided so that app developers need not change app specific
   initialization section every time except for a call to IDisplay_InitAppData(). 
   This is done as follows: InitAppData() is called to initialize AppletData 
   instance. It is app developers responsibility to fill-in app data initialization 
   code of InitAppData(). App developer is also responsible to release memory 
   allocated for data contained in AppletData -- this can be done in 
   IDisplay_FreeAppData().

PROTOTYPE:
   int AEEClsCreateInstance(AEECLSID ClsId,IShell * pIShell,IModule * po,void ** ppObj)

PARAMETERS:
	clsID: [in]: Specifies the ClassID of the applet which is being loaded

	pIShell: [in]: Contains pointer to the IShell object. 

	pIModule: pin]: Contains pointer to the IModule object to the current module to which
	this app belongs

	ppObj: [out]: On return, *ppObj must point to a valid IApplet structure. Allocation
	of memory for this structure and initializing the base data members is done by AEEApplet_New().

DEPENDENCIES
  none

RETURN VALUE
  AEE_SUCCESS: If the app needs to be loaded and if AEEApplet_New() invocation was
     successful
  EFAILED: If the app does not need to be loaded or if errors occurred in 
     AEEApplet_New(). If this function returns FALSE, the app will not be loaded.

SIDE EFFECTS
  none
===========================================================================*/
int AEEClsCreateInstance(AEECLSID ClsId, IShell *pIShell, IModule *po, void **ppObj)
{
	*ppObj = NULL;

	if( ClsId == AEECLSID_PONG )
	{
		// Create the applet and make room for the applet structure
		if( AEEApplet_New(sizeof(pong), ClsId, pIShell, po, (IApplet**)ppObj, (AEEHANDLER)pong_HandleEvent, (PFNFREEAPPDATA)pong_FreeAppData) )                       
		{
			//Initialize applet data, this is called before sending EVT_APP_START
         // to the HandleEvent function
			if(pong_InitAppData((pong*)*ppObj))
			{
				//Data initialized successfully
				return(AEE_SUCCESS);
			}
			else
			{
				//Release the applet. This will free the memory allocated for the applet when
				// AEEApplet_New was called.
				IAPPLET_Release((IApplet*)*ppObj);
				return EFAILED;
			}

        } // end AEEApplet_New
    }

	return(EFAILED);
}


/*===========================================================================
FUNCTION SampleAppWizard_HandleEvent

DESCRIPTION
	This is the EventHandler for this app. All events to this app are handled in this
	function. All APPs must supply an Event Handler.

PROTOTYPE:
	boolean SampleAppWizard_HandleEvent(IApplet * pi, AEEEvent eCode, uint16 wParam, uint32 dwParam)

PARAMETERS:
	pi: Pointer to the AEEApplet structure. This structure contains information specific
	to this applet. It was initialized during the AEEClsCreateInstance() function.

	ecode: Specifies the Event sent to this applet

   wParam, dwParam: Event specific data.

DEPENDENCIES
  none

RETURN VALUE
  TRUE: If the app has processed the event
  FALSE: If the app did not process the event

SIDE EFFECTS
  none
===========================================================================*/
static boolean pong_HandleEvent(pong* pMe, AEEEvent eCode, uint16 wParam, uint32 dwParam)
{  
   switch (eCode) 
	{
      // A key was pressed. Look at the wParam above to see which key was pressed. The key
      // codes are in AEEVCodes.h. Example "AVK_1" means that the "1" key was pressed.
      case EVT_KEY:
         switch( wParam )
         {
            case AVK_LEFT:
               if( pMe->pdlRect.x - 1 > 0 )
               {
                  IDISPLAY_EraseRect( pMe->pIDisplay, &pMe->pdlRect );
                  pMe->pdlRect.x -= 4;
                  IIMAGE_Draw( pMe->pPaddle, pMe->pdlRect.x, pMe->pdlRect.y );  
               }
               break;

            case AVK_RIGHT:
               if( (pMe->pdlRect.x + pMe->pdlRect.dx + 1) < pMe->DeviceInfo.cxScreen )
               {
                  IDISPLAY_EraseRect( pMe->pIDisplay, &pMe->pdlRect );
                  pMe->pdlRect.x += 4;
                  IIMAGE_Draw( pMe->pPaddle, pMe->pdlRect.x, pMe->pdlRect.y );  
               }
               break;
         }
         return(TRUE);

      // App is told it is starting up
      case EVT_APP_START:                        
         IDISPLAY_ClearScreen( pMe->pIDisplay );
         IIMAGE_Draw( pMe->pPaddle, pMe->pdlRect.x, pMe->pdlRect.y );  
         IIMAGE_Draw( pMe->pBall, pMe->balRect.x, pMe->balRect.y );
         IDISPLAY_Update( pMe->pIDisplay );

         // start the sim
         pMe->vBalX = 4;
         pMe->vBalY = -4; // TODO: make pos random?
         sim( pMe ); 
         return(TRUE);

      // App is told it is exiting
      case EVT_APP_STOP:
         return(TRUE);

      // App is being suspended 
      case EVT_APP_SUSPEND:
         return(TRUE);

      // App is being resumed
      case EVT_APP_RESUME:
         return(TRUE);

       default:
         break;
   }

   return FALSE;
}


// this function is called when your application is starting up
boolean pong_InitAppData(pong* pMe)
{
    // Get the device information for this handset.
    // Reference all the data by looking at the pMe->DeviceInfo structure
    // Check the API reference guide for all the handy device info you can get
    pMe->DeviceInfo.wStructSize = sizeof(pMe->DeviceInfo);
    ISHELL_GetDeviceInfo(pMe->a.m_pIShell,&pMe->DeviceInfo);

    // The display and shell interfaces are always created by
    // default, so we'll asign them so that you can access
    // them via the standard "pMe->" without the "a."
    pMe->pIDisplay = pMe->a.m_pIDisplay;
    pMe->pIShell   = pMe->a.m_pIShell;

    // Insert your code here for initializing or allocating resources...
    if( !(pMe->pPaddle = ISHELL_LoadResImage( pMe->pIShell, fRes, 5001 )) ||
        !(pMe->pBall   = ISHELL_LoadResImage( pMe->pIShell, fRes, 5002 )) )
    {
       return( FALSE );
    }

    // Setup bounding rects for images
    IIMAGE_GetInfo( pMe->pPaddle, &pMe->pdlInf ); 
    IIMAGE_GetInfo( pMe->pBall, &pMe->balInf ); 
    IIMAGE_SetParm( pMe->pBall, IPARM_ROP, AEE_RO_TRANSPARENT, 0 );
    
    pMe->pdlRect.x  = (pMe->DeviceInfo.cxScreen >> 1) - (pMe->pdlInf.cx >> 1);
    pMe->pdlRect.y  = pMe->DeviceInfo.cyScreen - pMe->pdlInf.cy;
    pMe->pdlRect.dx = pMe->pdlInf.cx;
    pMe->pdlRect.dy = pMe->pdlInf.cy;

    pMe->balRect.x  = (pMe->DeviceInfo.cxScreen >> 1) - (pMe->balInf.cx >> 1);
    pMe->balRect.y  = (pMe->DeviceInfo.cyScreen >> 1);
    pMe->balRect.dx = pMe->balInf.cx;
    pMe->balRect.dy = pMe->balInf.cy;
         
    // if there have been no failures up to this point then return success
    return TRUE;
}

// this function is called when your application is exiting
void pong_FreeAppData(pong* pMe)
{
   IIMAGE_Release( pMe->pPaddle );
   IIMAGE_Release( pMe->pBall );
}

// physical simulation
void sim( pong* pMe )
{
   int nx = 0, ny = 0;
   int vpx, vpy;
   int vnx, vny;
   int dot;

   // clock must be reset each round
   ISHELL_SetTimer( pMe->pIShell, SIM_CLOCK, sim, pMe );

   // check for collisions and update ball velocity
   if( pMe->balRect.x + pMe->balRect.dx + pMe->vBalX > pMe->DeviceInfo.cxScreen ) // hits right side of sceen
      nx = -1;
   else if( pMe->balRect.x + pMe->vBalX < 0 ) // hits left side of screen
      nx = 1;
   else if( pMe->balRect.y + pMe->vBalY < 0 ) // hits top side of screen
      ny = 1;
   else if( pMe->balRect.y + pMe->balRect.dy + pMe->vBalY > pMe->pdlRect.y && 
            ((pMe->balRect.x > pMe->pdlRect.x && pMe->balRect.x < pMe->pdlRect.x + pMe->pdlRect.dx) ||
            (pMe->balRect.dx > pMe->pdlRect.x && pMe->balRect.dx < pMe->pdlRect.x + pMe->pdlRect.dx)) ) 
   {
      ny = -1;  // hits the paddle
   }
   else if( pMe->balRect.y + pMe->vBalY > pMe->DeviceInfo.cyScreen ) // end game case, ball's in the drink
   {
      ISHELL_MessageBox( pMe->pIShell, fRes, IDS_GAME_OVER, IDS_YOU_SUCK );
      ISHELL_CloseApplet( pMe->pIShell, FALSE );
   }

   if( nx || ny ) // normal vector reflection
   {
      dot = nx * pMe->vBalX + ny * pMe->vBalY;
      vnx = dot * nx;
      vny = dot * ny;
      vpx = pMe->vBalX - vnx;
      vpy = pMe->vBalY - vny;
      pMe->vBalX = vpx - vnx;
      pMe->vBalY = vpy - vny;
   }

   // move/render ball
   IDISPLAY_EraseRect( pMe->pIDisplay, &pMe->balRect );
   pMe->balRect.x += pMe->vBalX;
   pMe->balRect.y += pMe->vBalY;
   IIMAGE_Draw( pMe->pBall, pMe->balRect.x, pMe->balRect.y );  
   IDISPLAY_Update( pMe->pIDisplay ); 
}
