#include "add_server_wizard.h"
#include "../../RWADBusAdaptor.h"
#include <QDebug>
#include <QtDBus>
#include <QDBusPendingCallWatcher>

Add_Server_wizard::Add_Server_wizard(QObject *parent) : QObject(parent) {
    _initDBus();


}

bool Add_Server_wizard::processStep1(QString host_url) {
    qDebug() << "Processing Step 1 with args: " << host_url;

    if(host_url == "") {
        emit step1Failed(tr("This field can't be empty!"));
        return false;
    }

    return _add_server(host_url);
}

bool Add_Server_wizard::processStep2() {
    qDebug() << "Processing Step 2 with args: No Args.";
    emit step2Failed(tr("The feature you expected here are not yet implemented."));
    // Just show placeholder scene now.
    emit step2Success();
    return false;
}

bool Add_Server_wizard::_add_server(QString host_url) {
    return _add_web_app_host(host_url);
}

void Add_Server_wizard::_initDBus() {
    if (!QDBusConnection::sessionBus().isConnected()) {
        qCritical() << "Cannot connect to the D-Bus session bus.";
    }

    // Create DBus object
    _dbus_rwa = new OrgArcticaProjectRWASupportSessionServiceInterface("org.ArcticaProject.RWASupportSessionService", "/RWASupportSessionService",
                               QDBusConnection::sessionBus(), this->parent());

    qDebug("Initialized DBus object!");
}

bool Add_Server_wizard::_add_web_app_host(QString host_url) {
    qDebug() << "Requesting D-Bus session service to add a new host: " << host_url;

    // Make an asynchrous 'add_web_app_host' call (Response will be sent to '_add_web_app_host_dbus_replied')
    QDBusPendingCall async = _dbus_rwa->asyncCall("add_web_app_host", host_url);
    QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(async, this);

    QObject::connect(watcher, SIGNAL(finished(QDBusPendingCallWatcher*)),
                     this, SLOT(_add_web_app_host_dbus_replied(QDBusPendingCallWatcher*)));

    return true;
}

void Add_Server_wizard::_add_web_app_host_dbus_replied(QDBusPendingCallWatcher *call) {
    QString result = "";

    QDBusPendingReply<QString> reply = *call;
    if (reply.isError()) {
        qDebug() << "D-Bus 'add_web_app_host' request failed, this was the reply:";
        qDebug() << reply.error();
        return;
    } else {
        result = reply.argumentAt<0>();
    }
    call->deleteLater();

    qDebug() << "Raw JSON from starting session is:" << result.toUtf8().replace('"', "");
    QJsonDocument doc = QJsonDocument::fromJson(result.toUtf8());

    // Get the QJsonObject
    QJsonObject jObject = doc.object();
    QVariantMap mainMap = jObject.toVariantMap();

    // Status of request
    QString request_status = mainMap["status"].toString();
    if (request_status == "success") {
        qDebug() << "Successfully started a Session.";
        emit step1Success();
    } else {
        qCritical() << "An error occured while adding a new host!";

        QString reason = "An error occured while adding a new host!";
        QString type = mainMap["type"].toString();
        if(type == "connection"){
            reason = tr("Couldn't connect to the specified host!");
        } else if (type == "duplicate") {
            reason = tr("The specified host was already added!");
        } else if (type == "invalid_url") {
            reason = tr("The specified host address is not valid!");
        }
        emit step1Failed(reason);
    }
}
