/***
 * Warthog Robotics
 * University of Sao Paulo (USP) at Sao Carlos
 * http://www.warthog.sc.usp.br/
 *
 * This file is part of WRJoy project.
 *
 * 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 3 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, see <http://www.gnu.org/licenses/>.
 ***/

// Includes class header
#include <WRJoy/joystickmanager.hh>

// Includes Qt library
#include <QtCore/QtCore>
#include <QtWidgets/QtWidgets>

// Includes WRJoy
#include <WRJoy/wrjoy.hh>

// Selects WRJoy namespace
using namespace WRJoy;


WRJoy::JoystickManager::~JoystickManager() {
    this->reset();
}


void WRJoy::JoystickManager::addJoystick(QString joystickName) {
    _joysticks << new Joystick(joystickName, true);
}

void WRJoy::JoystickManager::delJoystick(QString joystickName) {
    qint16 joystickIndex = this->joystickIndex(joystickName);
    if (joystickIndex != -1) {
        Joystick* joystick = _joysticks.at(joystickIndex);
        delete(joystick);
        _joysticks.removeAt(joystickIndex);
    }
}

QWidget* WRJoy::JoystickManager::joystickWidget(quint8 joystickNumber) {
    return(_joysticks.at(joystickNumber)->widget());
}


QList<Joystick*> WRJoy::JoystickManager::joysticks() {
    return(_joysticks);
}

void WRJoy::JoystickManager::stopAllJoysticks() {
    QListIterator<Joystick*> it(_joysticks);
    while (it.hasNext()){
        it.next()->stop();
    }
}

void WRJoy::JoystickManager::reset() {
    QListIterator<Joystick*> it(_joysticks);
    while (it.hasNext())
        delete(it.next());

    _joysticks.clear();
}

qint16 WRJoy::JoystickManager::joystickIndex(QString joystickName) {
    QListIterator<Joystick*> it(_joysticks);
    Joystick* joystick = 0;
    bool found = false;
    while (it.hasNext()){
        joystick = it.next();
        if (joystick->name() == joystickName) {
            found = true;
            it.toBack();
        }
    }

    qint16 index = -1;
    if (found) {
        index = _joysticks.indexOf(joystick);
    }

    return(index);
}
