#include "../headers/scstwappbackend.h"

ScStwAppBackend::ScStwAppBackend(QObject *parent) : QObject(parent)
{
}

// ------------------------
// --- helper functions ---
// ------------------------

void ScStwAppBackend::setScStwClient(ScStwClient *client) {
    if(client != this->scStwClient) {
        this->scStwClient = client;
        emit this->scStwClientChanged();
    }
}

// - athlete management -

// TODO: move to client
QVariant ScStwAppBackend::getAthletes() {
    QVariantMap reply = this->scStwClient->sendCommand(4003);

    if(reply["status"] != 200){
        //handle Error!!
        qDebug() << "+ --- error getting athletes: " << reply["status"];
        return false;
    }

    QVariantMap tmpAthletes = reply["data"].toMap();

    //qDebug() << tmpAthletes;

    return tmpAthletes;
}

bool ScStwAppBackend::createAthlete(QString userName, QString fullName) {

    QVariant requestData = QVariantMap({{"fullName", fullName}, {"userName", userName}});

    QVariantMap reply = this->scStwClient->sendCommand(4001, requestData.toJsonValue());

    if(reply["status"] != 200){
        //handle Error!!
        qDebug() << "+ --- error creating athlete: " << reply["status"];
        return false;
    }

    return true;
}

bool ScStwAppBackend::deleteAthlete( QString userName ){

    QVariant requestData = QVariantMap({{"userName", userName}});

    QVariantMap reply = this->scStwClient->sendCommand(4002, requestData.toJsonValue());

    if(reply["status"] != 200){
        //handle Error!!
        qDebug() << "+ --- error deleting athlete: " << reply["status"];
        return false;
    }

    return true;

}

bool ScStwAppBackend::selectAthlete( QString userName, int timerId ){

    QVariant requestData = QVariantMap({{"userName", userName}, {"timerId", timerId}});

    QVariantMap reply = this->scStwClient->sendCommand(4000, requestData.toJsonValue());

    if(reply["status"] != 200){
        //handle Error!!
        qDebug() << "+ --- error selecting athlete: " << reply["status"];
        return false;
    }

    return true;

}

QVariant ScStwAppBackend::getResults( QString userName ){
    QVariantMap reply = this->scStwClient->sendCommand(4004, userName);

    if(reply["status"] != 200){
        //handle Error!!
        qDebug() << "+ --- error getting results: " << reply["status"];
        return false;
    }

    QVariantList tmpAthletes = reply["data"].toList();

    //qDebug() << tmpAthletes;

    return tmpAthletes;
}

// -------------------------
// --- functions for qml ---
// -------------------------

ScStwClient* ScStwAppBackend::getScStwClient() {
    return this->scStwClient;
}
