#include "eventslistwidget.h"
#include <QtConcurrent/QtConcurrent>
#include <QLabel>
#include <QStringList>
#include <QSpacerItem>
#include <widgets/newspiece.h>

EventsListWidget::EventsListWidget(QWidget *parent) : QWidget(parent)
{
    event_downloader.targetBytearray = &events_data;
    event_downloader.setUrl(QUrl("http://translate.lotros.ru/events/get/1"));

    event_layout = new QVBoxLayout(this);
    event_layout->setSpacing(7);
    event_layout->setObjectName(QStringLiteral("events_layout"));
    event_layout->setContentsMargins(11, 11, 11, 0);

    connect(&event_update_timer, &QTimer::timeout, &event_downloader, &Downloader::start);
    connect(&event_downloader, &Downloader::downloadFinished, this, &EventsListWidget::updateEvents);
    emit event_downloader.start();
    event_update_timer.setInterval(1000 * 60); // 60 seconds;
    event_update_timer.start();
}

EventsListWidget::~EventsListWidget()
{
    event_update_timer.stop();
}

void EventsListWidget::updateEvents()
{
    if (!qApp)
        return;

    qDebug() << "Received data: " << QString(events_data);

    if (events_data.size() == 0) {
        constructEventPiece(0, "Не могу загрузить список событий", "Загрузка списка событий не удалась. Чтобы просмотреть текущие игровые события, перейдите на <a href='http://translate.lotros.ru/'>http://translate.lotros.ru/</a>", "http://translate.lotros.ru/", "");
        return;
    }

    QStringList events_list = QString(events_data).split("|");
    events_data.clear();

    for (int i = 0; i < events_list.size(); i++) {
        QStringList event_piece = events_list[i].split(":::");

        qDebug() << "Processing event " << event_piece;

        QString title = event_piece[0];
        QString img_src = event_piece[1];
        QString desrc = event_piece[2];
        QString date_begin = event_piece[3];
        QString date_end = event_piece[4];
        QString date_formatted = event_piece[5];

        constructEventPiece(i, title, desrc, "", date_formatted);

        QtConcurrent::run([i, this, img_src](){
            Downloader img_dwnld;
            QByteArray img = "";
            img_dwnld.setUrl(QUrl(img_src));
            img_dwnld.targetBytearray = &img;
            img_dwnld.start();
            img_dwnld.waitForDownloaded();
            qDebug() << "Downloaded " << img_src;
            QPixmap img_pixmap;
            img_pixmap.loadFromData(img);
            QMetaObject::invokeMethod(this, "setImgToEventPiece", Qt::QueuedConnection, Q_ARG(int, i), Q_ARG(QPixmap, img_pixmap));
        });
    }
}

void EventsListWidget::constructEventPiece(int piece_id, QString title, QString text, QString news_src, QString news_date)
{
    NewsPiece* old_piece = findChild<NewsPiece*>("event_piece_" + QString::number(piece_id));

    if (old_piece) {
        event_layout->removeWidget(old_piece);
        old_piece->deleteLater();
    }

    NewsPiece* news_piece = new NewsPiece(this);
    news_piece->setObjectName(QStringLiteral("event_piece_") + QString::number(piece_id));
    news_piece->setIcon(QPixmap(QString::fromUtf8(":/appicon.ico")).scaled(40, 40));
    news_piece->setTitle(title, news_src);
    news_piece->setContents(text);
    news_piece->setDate(news_date);

    event_layout->addWidget(news_piece, piece_id, 0);
}

void EventsListWidget::setImgToEventPiece(int piece_id, QPixmap img)
{
    NewsPiece* piece = findChild<NewsPiece*>("event_piece_" + QString::number(piece_id));
    if (!piece)
        return;
    piece->setIcon(img);
}
