#include <Sample.h>

#include <QCoreApplication>
#include <QDebug>
#include <QUrl>
#include <QtNetwork/QNetworkRequest>

Sample::Sample(QObject *parent)
    : QObject(parent), _manager(new QNetworkAccessManager(this))
{
    connect(this->_manager, SIGNAL(sslErrors(QNetworkReply*, const QList<QSslError>&)),
            this, SLOT(sslErrors(QNetworkReply *, const QList<QSslError>&)));
}

void Sample::startTest()
{
    makeRequest();
}

void Sample::makeRequest()
{
    QUrl request("https://api.gamenet.ru:8443/restapi?method=games.getMaintenance");

    QNetworkReply *reply = (1 == 1)
        ? this->_manager->get(QNetworkRequest(request))
        : this->_manager->post(QNetworkRequest(request), request.encodedQuery());

    connect(reply, SIGNAL(finished()), this, SLOT(onRequestFinish()));
    connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(onError(QNetworkReply::NetworkError)));

    qDebug() << "makeRequest" << request;
}

void Sample::onRequestFinish()
{
    qDebug() << "onRequestFinish";

    QNetworkReply *reply = qobject_cast<QNetworkReply*>(QObject::sender());
    reply->deleteLater();

    QString response = QString::fromUtf8(reply->readAll());
    QNetworkReply::NetworkError error = reply->error();

    qDebug() << response << error;
}

void Sample::onError(QNetworkReply::NetworkError error)
{
    qDebug() << "error" << error;
}

void Sample::sslErrors(QNetworkReply *reply, const QList<QSslError> &errors)
{
    qDebug() << "sslErrors";
    Q_FOREACH(QSslError error, errors) {
        qDebug() << error;
    }

    reply->ignoreSslErrors();
}

void Sample::onTimer()
{
    QCoreApplication::quit();
}


