/**
* \file joystick_SDL.cpp
* \author basile.graf@epfl.ch
* 
* This file contains stuff related to the joystick. Cross-platform thanks to SDL.
*/


#include "SDL.h"
#include "joystick_SDL.h"


int numJoy; // number of joystick available
int numAxes;
int thereIsJoy=0;
SDL_Joystick* joystick;
	
	
///Joystick initialisation
/**
* This function tries to open the joystick if one is connected. If no joystick 
* is found, the programm uses keyboard controll
*/
int joystick_init()
{
	int dummy;
	
	if ( SDL_Init(SDL_INIT_VIDEO|SDL_INIT_JOYSTICK) < 0 )
	{
		fprintf(stderr, "Couldn't initialize joystick: %s\n",SDL_GetError());
	}
	
	numJoy = SDL_NumJoysticks();
	
	printf("Number of joysticks: %d \n", numJoy);
	
	if (numJoy>0)
	{
		joystick = SDL_JoystickOpen(0); //use first joystick, if any
		numAxes = SDL_JoystickNumAxes (joystick);
		printf( "Joystick found, Number of axes: %d, name: %s \n", numAxes, SDL_JoystickName(0));
		dummy = SDL_JoystickEventState(SDL_QUERY);
		thereIsJoy=1;
	}
	else
	{
		fprintf( stderr, "No Joystick could be opened!! \n");
		thereIsJoy=0;
	}
	
	return 1;
}



///Get joystick position
/**
* Returns the actual joystick position (of selected axes via corresponding boolean doX...Z)
* \param doX : TRUE: get X position and modify the *X value. FALSE: Do not modify *X.
* \param doY : TRUE: get Y position and modify the *Y value. FALSE: Do not modify *Y.
* \param doZ : TRUE: get Z position and modify the *Z value. FALSE: Do not modify *Z.
* \param doR : TRUE: get R position and modify the *R value. FALSE: Do not modify *R.
* \param *X :  Adress of the X value to be modified or not.
* \param *Y :  Adress of the Y value to be modified or not.
* \param *Z :  Adress of the Z value to be modified or not.
* \param *R :  Adress of the R value to be modified or not.
*/
void joystick_getXYZR(float *X, float *Y, float *Z, float *R, bool doX, bool doY, bool doZ, bool doR)
{
	if (SDL_JoystickOpened(0))
	{
		if (numAxes>0 && doX) *X = (float(SDL_JoystickGetAxis(joystick, 0))/32768.0f);
		if (numAxes>1 && doY) *Y = (float(SDL_JoystickGetAxis(joystick, 1))/32768.0f);
		if (numAxes>2 && doZ) *Z = (float(SDL_JoystickGetAxis(joystick, 2))/32768.0f);
		if (numAxes>3 && doR) *R = (float(SDL_JoystickGetAxis(joystick, 3))/32768.0f);
	}
}



///Close joystick
/**
* If a joystick has been opened, this function closes it...
*/
void joystick_close()
{
	if (numJoy>0)
	{
		SDL_JoystickClose(joystick); // Close joystick, if any
		printf("Joystick closed.");
	}
}


///Does a joystick exists?
/**
* \return : 1 => there is one.    0 => there is no joystick.
*/
int is_there_a_joystick()
{
	return thereIsJoy;
}