#include "dchublinklistener.h"

#include <QDir>
#include <QFile>
#include <QTimerEvent>

DCHubLinkListener *DCHubLinkListener::pHubLinkListener = NULL;

DCHubLinkListener::DCHubLinkListener(QWidget *parent) : QWidget(parent) {
    QString homepath = QDir::homePath();
    QString eis_path = homepath + "/.eiskaltdc";
    file = new QFile(QString(eis_path + "/eiskaltdc.hublink"));
    timerId = startTimer(1000);
}

DCHubLinkListener::~DCHubLinkListener() {
    killTimer(timerId);
    delete file;
}

void DCHubLinkListener::timerEvent(QTimerEvent *event) {
    if (event->timerId() == timerId) {
        testFile();
    } else {
        QWidget::timerEvent(event);
    }
}

void DCHubLinkListener::testFile() {
    if (file->exists()) {
        if (file->open(QIODevice::ReadOnly)) {
            QString link = file->readLine();
            file->close();
            file->remove();
            connect(link);
        }
    }
}

void DCHubLinkListener::connect(QString hub) {
    if (hub.indexOf("dchub://") != 0)
        return;

    hub.replace("\n", "");
    hub.replace("dchub://", "");
    hub = hub.trimmed();

    if (hub != "")
        DCConnectionManager::Instance()->Connect(CString(), hub.toAscii().constData());
}
