/****************************************************************************
 * START Wiimotes
 *
 * All functions to syncronize with Wiimotes are in this module
 ****************************************************************************/

#include <gccore.h>
#include <sdcard.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <ogcsys.h>

#include "wiiuse/wiiuse.h"

//Wiimotes
wiimote** wiimotes;
wiimote** wiimotes2;



//Buttons of Wiimote
unsigned int button1M=0;//Variable of button 1
unsigned int button2M=0;//Variable of button 2
unsigned int upM=0;//Variable of button up
unsigned int downM=0;//Variable of button down

//Variable to detect if there is a second Wiimote connected
int pad2=0;



//This function return the Wiimote
struct wiimote_t* get_wm(int pad)
{


if (pad2==1)
{
	if (pad==0)
		return wiimotes[pad];
	else 
		return wiimotes2[0];
}
else
	return wiimotes[pad];

}


//Here control events wiimote (only for the menu)
void wiimote_event(struct wiimote_t* wm, int event) {


	switch (event) {
		case WIIUSE_EVENT:
		
			button2M=0;
			button1M=0;
			upM=0;
			downM=0;



//Classic Control
			if (wm->exp.type == EXP_CLASSIC) {
					/* classic controller */
					struct classic_ctrl_t* cc = (classic_ctrl_t*)&wm->exp.classic;


				if (IS_JUST_PRESSED(cc, CLASSIC_CTRL_BUTTON_A))
					button1M=1;
				if (IS_JUST_PRESSED(cc, CLASSIC_CTRL_BUTTON_B))
					button2M=1;

				if (IS_JUST_PRESSED(cc, CLASSIC_CTRL_BUTTON_UP))
					upM=1;
				if (IS_JUST_PRESSED(cc, CLASSIC_CTRL_BUTTON_DOWN))
					downM=1;
			}


//Wiimote


			if (IS_JUST_PRESSED(wm, WIIMOTE_BUTTON_TWO)) 
				button2M=1;
			if (IS_JUST_PRESSED(wm, WIIMOTE_BUTTON_ONE)) 
				button1M=1;

			if (IS_JUST_PRESSED(wm, WIIMOTE_BUTTON_RIGHT))
				upM=1;
			if (IS_JUST_PRESSED(wm, WIIMOTE_BUTTON_LEFT))
				downM=1;
			
					
			break;
	}
}



void disconnect_wm()
{

	bte_init();
	bte_start();

}


//This function start the Wiimote
void start_wm (int pad)
{

//If wiimote 1
if (pad==0)
{
	bte_init();
	bte_start();

	wiimotes =  wiiuse_init(4, wiimote_event);
	wiiuse_find(wiimotes, 4, 5);
	wiiuse_connect(wiimotes, 4);
	wiiuse_set_leds(wiimotes[0], WIIMOTE_LED_1);
	wiiuse_rumble(wiimotes[0], 1);
	usleep(500000);
	wiiuse_rumble(wiimotes[0], 0);
	wiiuse_set_ir(wiimotes[0], 0);
	wiiuse_set_leds(wiimotes[0], WIIMOTE_LED_1);

}
//If Wiimote 2
else
{


	wiimotes2 =  wiiuse_init(4, wiimote_event);
	wiiuse_find(wiimotes2, 4, 5);
	wiiuse_connect(wiimotes2, 4);
	wiiuse_set_leds(wiimotes2[0], WIIMOTE_LED_2);
	wiiuse_rumble(wiimotes2[0], 1);
	usleep(500000);
	wiiuse_rumble(wiimotes2[0], 0);
	wiiuse_set_ir(wiimotes2[0], 0);
	wiiuse_set_leds(wiimotes2[0], WIIMOTE_LED_2);

	//Wiimote 2 connected.
	pad2=1;

}

}






