/*
 * Copyright (C) 2007-2008 Arnaud Ysmal <wiidevel@stacktic.org>
 *
 * wiimotefunctions.c (TransferMii)
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 */

#include <stdlib.h>
#include <stdio.h>

#ifdef CWIID_STATIC
	#include "../cwiid/cwiid.h"
#else
	#include <cwiid.h>
#endif

#include "tmii.h"

extern unsigned char miiblock[BLOCK_SIZE];

bool wm_update = FALSE;
bool wm_read = FALSE;
bool wm_connected = FALSE;
bool wm_auto_update = FALSE;

cwiid_wiimote_t *wm;
bdaddr_t ba = *BDADDR_ANY;
cwiid_mesg_callback_t *callback;

/* Disconnects the wiimote (called by wconnect() by atexit)*/
void wiimoteDisconnect()
{
	if (!wm_connected)
		return;
	if (wm_auto_update && wm_update)
		wiimoteWrite();
	printf("Disconnecting...\n");

	wm_connected=cwiid_close(wm);
	wm_read = wm_update = FALSE;
}

/* Looks for a wiimote */
bool wiimoteConnect()
{
	if (wm_connected)
		return TRUE;
	printf("Looking for a wiimote... (please press 1+2 on the wiimote)\n");
	if (!(wm = cwiid_open(&ba, CWIID_FLAG_MESG_IFC)))
		return FALSE;
	cwiid_set_led(wm, CWIID_LED1_ON|CWIID_LED4_ON);

	atexit(wiimoteDisconnect);
	return (wm_connected=TRUE);
}

/* Fills miiblock with mii block from wiimote EEPROM */
bool wiimoteRead()
{
	if (!wm_connected && !wiimoteConnect())
		return FALSE;
	printf("Reading block from the wiimote...\n");
        if (wm_read)
		return TRUE;
	
	return wm_read=(!cwiid_read(wm, CWIID_RW_EEPROM,
			     FIRST_BLOCK, BLOCK_SIZE,
			     miiblock));
}

/* Writes miiblock to wiimote EEPROM */
bool wiimoteWrite()
{
	if (!wm_update)
		return TRUE;
	if (!wm_connected && !wiimoteConnect())
		return FALSE;


	crcCheck();

	printf("Writing block to the wiimote EEPROM...\n");
	wm_update = FALSE;

	return !(cwiid_write(wm, CWIID_RW_EEPROM,
			       FIRST_BLOCK, BLOCK_SIZE, miiblock) ||
		 cwiid_write(wm, CWIID_RW_EEPROM,
			       SECOND_BLOCK, BLOCK_SIZE, miiblock));
}

/* Looks for an empty slot */
int nextEmptySlot()
{
	int i;
	
	if (!wm_read && !wiimoteRead())
		return FALSE;
	for (i=1; i<=MII_NB && !miiIsEmpty(i); i++)
		;
	return i>MII_NB?0:i;
}
