/*!
  \file
  \brief Wiimote ドライバのリロード

  \author Satofumi KAMIMURA

  $Id: rescanWiimote.cpp 774 2009-05-05 08:02:57Z satofumi $
*/

#include "rescanWiimote.h"
#include "DetectOS.h"
#ifdef LINUX_OS
bool qrk::rescanWiimote(void)
{
  // !!! 実装方法、未検討
  return false;
}
#else
#include <windows.h>
#include <bthsdpdef.h>
#include <bthdef.h>
#include <BluetoothAPIs.h>
#include <string>
#include <vector>

#pragma comment (lib, "Irprops.lib")

using namespace qrk;


// Wii リモコン用ドライバのリロード
bool qrk::rescanWiimote(void)
{
  // Bluetooth デバイス名の取得。ただし、接続中のデバイスは無視する
  BLUETOOTH_DEVICE_SEARCH_PARAMS btsp;
  ZeroMemory(&btsp, sizeof(BLUETOOTH_DEVICE_SEARCH_PARAMS));
  btsp.dwSize = sizeof(BLUETOOTH_DEVICE_SEARCH_PARAMS);
  btsp.fReturnAuthenticated = TRUE;
  btsp.fReturnRemembered = TRUE;
  btsp.fReturnUnknown = TRUE;
  btsp.fReturnConnected = TRUE;
  btsp.fIssueInquiry = TRUE;
  btsp.cTimeoutMultiplier = 2;
  btsp.hRadio = NULL;

  BLUETOOTH_DEVICE_INFO btdi;
  btdi.dwSize = sizeof(btdi);

  HBLUETOOTH_DEVICE_FIND hbf = BluetoothFindFirstDevice(&btsp, &btdi);
  if (hbf == NULL) {
    //fprintf(stderr, "hFind is NULL\n");
    return false;
  }

  typedef vector<BLUETOOTH_DEVICE_INFO*> WiiDevices;
  WiiDevices devices;
  do {
    // 接続中以外の Wii デバイスを登録
    if (btdi.fConnected == 0) {
      char device_name[MAX_PATH];
      int i = 0;
      while (btdi.szName[i] != '\0') {
	device_name[i] = static_cast<char>(btdi.szName[i]);
	++i;
      }
      device_name[i] = '\0';
      //fprintf(stderr, "%d: %s\n", btdi.fConnected, device_name);

      if (! strcmp(device_name, "Nintendo RVL-CNT-01")) {
	devices.push_back(&btdi);
	//fprintf(stderr, "register: %p\n", &btdi);
      }
    }
  } while (BluetoothFindNextDevice(hbf, &btdi) != FALSE);
  BluetoothFindDeviceClose(hbf);

  // Bluetooth デバイスのアンロード
  for (WiiDevices::iterator it = devices.begin(); it != devices.end(); ++it) {

    BluetoothRemoveDevice(&(*it)->Address);
  }

  // 接続有効化
  HANDLE hRadio;
  BLUETOOTH_FIND_RADIO_PARAMS btfrp = { sizeof(btfrp) };
  HBLUETOOTH_RADIO_FIND hbtrf = BluetoothFindFirstRadio(&btfrp, &hRadio);
  if (hbtrf == NULL) {

    //fprintf(stderr, "BluetoothFindFirstRadio() is NULL\n");
    return false;
  }
  do {
    BLUETOOTH_RADIO_INFO radioInfo;
    radioInfo.dwSize = sizeof(radioInfo);
    BluetoothGetRadioInfo(hRadio, &radioInfo);

    for (WiiDevices::iterator it = devices.begin(); it != devices.end(); ++it) {

      BluetoothSetServiceState(hRadio, *it,
			       &HumanInterfaceDeviceServiceClass_UUID,
			       BLUETOOTH_SERVICE_ENABLE );
    }

  } while (BluetoothFindNextRadio(hbtrf, &hRadio));
  BluetoothFindRadioClose(hbtrf);

  return true;
}
#endif
