#include "mythwiimote.h"
#include <QtPlugin>
#include <QKeyEvent>
#include <QFile>
#include <QtGlobal>
#include <QDebug>
#include <QStringList>
#include <QDir>
#include <bluetooth/bluetooth.h>
#include <cwiid.h>
#include <wiimote.h>





MythWiimote::MythWiimote()
    :m_inputManager(0),
    m_lastWiimoteId(0)
{
    cwiid_set_err(NULL);
};

MythWiimote::~MythWiimote()
{
}

void MythWiimote::setInputManager(MythInputManagerInterface * inputManager)
{
    if (inputManager==NULL)
        stop();
    m_inputManager=inputManager;

    connect(this, SIGNAL(logDebug(const QString &)),m_inputManager,SLOT(logDebug(const QString &)));
    connect(this, SIGNAL(logInfo(const QString &)),m_inputManager,SLOT(logInfo(const QString &)));
    connect(this, SIGNAL(logWarning(const QString &)),m_inputManager,SLOT(logWarning(const QString &)));
    connect(this, SIGNAL(logError(const QString &)),m_inputManager,SLOT(logError(const QString &)));
}

void MythWiimote::start()
{
    if (m_inputManager==NULL)
    {
        qWarning() << QString("MythWiimote can not start without an input manager");
        return;
    }
    moveToThread(this);
    QThread::start();

}
void MythWiimote::stop()
{
}

const QString MythWiimote::name() const
{
    return "wiimote";
}

const QString MythWiimote::description() const
{
    return "wiimote aka Wii Remote support for Mythtv";
}

void MythWiimote::run()
{
    QTimer searchTimer; 
    m_inputManager->logWarning("start mythwiimote service");
    searchTimer.setInterval(1000);
    connect(&searchTimer,SIGNAL(timeout()),this,SLOT(searchWiimote()));
    searchTimer.start();
    QThread::exec();
    
}

void MythWiimote::searchWiimote()
{

    int bdinfo_count;
	struct cwiid_bdinfo *bdinfo;
    uint8_t flags = 0;
	//char ba_str[18];

	if ((bdinfo_count = cwiid_get_bdinfo_array(-1, 2, -1, &bdinfo, flags))
	  == -1) {
        if (!m_noBluetoothmsg) 
            m_inputManager->logWarning("MythWiimote: No bluetooth adapter found");
        else
            m_inputManager->logDebug("MythWiimote: No bluetooth adapter found");
        m_noBluetoothmsg=true;
		return;
	}
    m_noBluetoothmsg=false;

    QThread::msleep(1000);

    //we connect to the first one only at the moment
    if (bdinfo_count>0)
    {
        onWiimoteDiscovered(bdinfo[0]);
    }
    else
        m_inputManager->logDebug("MythWiimote: No wiimote detected");
}


// and new wii mote have been discovered
void MythWiimote::onWiimoteDiscovered(cwiid_bdinfo infoWiimote)
{
    m_lastWiimoteId++;
    if (m_lastWiimoteId>15)m_lastWiimoteId=1;
    Wiimote * newWiimote = new Wiimote(m_inputManager,infoWiimote,m_lastWiimoteId);
    connect(newWiimote,SIGNAL(onDisconnected(Wiimote *)),this,SLOT(onWiimoteDisconnected(Wiimote *)));
    newWiimote->start();
}

void MythWiimote::onWiimoteDisconnected(Wiimote * wiimote)
{
    wiimote->deleteLater();
}





Q_EXPORT_PLUGIN2(mythinputwiimote, MythWiimote);
