#include "dchublinklistener.h"

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

DCHubLinkListener *g_pHubLinkListener = 0;

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

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

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 != "")
	g_pConnectionManager->Connect(CString(), hub.toAscii().constData());
}
