#include <QNetworkAccessManager>
#include <QUrl>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QAuthenticator>
#include <QXmlReader>
#include <QXmlInputSource>

#include "Scoreboard.h"
#include "ScoreboardHandler.h"

Scoreboard::Scoreboard() {
    _script = QUrl("http://yourserver/yourserver.com");
    _manager = new QNetworkAccessManager(this);
    connect(_manager, SIGNAL(authenticationRequired(QNetworkReply*, QAuthenticator*)), this, SLOT(authenticate(QNetworkReply*, QAuthenticator*)));
}

void Scoreboard::authenticate(QNetworkReply*, QAuthenticator *auth) {
    auth->setUser("user");
    auth->setPassword("password");
    return;
}

void Scoreboard::postIsReady( QNetworkReply * reply) {
    if (reply->error()==0) {
        emit boardSubmitSuccess(_score);
    } else {
        emit boardSubmitError();
    }
    disconnect(_manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(postIsReady(QNetworkReply*)));
    getList();
}

void Scoreboard::fileIsReady( QNetworkReply * reply) {

    if (reply->error()==0) {

        QXmlSimpleReader xmlReader;

        Handler *handler = new Handler;
        xmlReader.setContentHandler(handler);
        xmlReader.setErrorHandler(handler);

        QXmlInputSource *source = new QXmlInputSource();
        source->setData(reply->readAll());
        bool ok = xmlReader.parse(source);

        if (ok) {
            emit boardChanged(handler->getData());
        }

    } else {
        emit boardError();
    }
    disconnect(_manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(fileIsReady(QNetworkReply*)));

}

void Scoreboard::getList() {
    connect(_manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(fileIsReady(QNetworkReply*)));
    _manager->get(QNetworkRequest(_script));
}

void Scoreboard::submitScore(QString name, int score) {
    _score = score;
    connect(_manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(postIsReady(QNetworkReply*)));
    QByteArray data;
    data.append("name="+name+"&score="+QString::number(score));
    _manager->post(QNetworkRequest(_script), data);
}
