#include "serverstatuswidget.h"
#include "ui_serverstatuswidget.h"

#include <QDebug>

ServerStatusWidget::ServerStatusWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::ServerStatusWidget)
{
    ui->setupUi(this);

    downloader.targetBytearray = &downloaded_data;
    downloader.setUrl(QUrl("http://translate.lotros.ru/servers.txt"));

    connect(&update_timer, &QTimer::timeout, &downloader, &Downloader::start);
    connect(&downloader, &Downloader::downloadFinished, this, &ServerStatusWidget::updateStatus, Qt::QueuedConnection);
    emit downloader.start();
    update_timer.setInterval(1000 * 60); // 1 minute;
    update_timer.start();
}

ServerStatusWidget::~ServerStatusWidget()
{
    delete ui;
}

void ServerStatusWidget::updateStatus()
{
    QStringList servers = QString(downloaded_data).split("|||");
    foreach (QString server, servers) {
        QStringList data = server.split(":::");
        QWidget* widget = findChild<QWidget*>(QString(data[0]).toLower() + "_common");
        qDebug() << data;
        if (!widget)
            continue;
        if (data.size() > 1 && data[1] == "on")
            widget->setStyleSheet(open_color);
        else
            widget->setStyleSheet(closed_color);
    }
    downloaded_data = "";
}
