#include "newslistwidget.h"
#include <QtConcurrent/QtConcurrent>
#include <QLabel>
#include <QStringList>
#include <QSpacerItem>
#include <widgets/newspiece.h>
#include "models/settings.h"

NewsListWidget::NewsListWidget(QWidget *parent) : QWidget(parent)
{
    news_downloader.targetBytearray = &news_data;
    news_downloader.setUrl(Settings::getValue("Network/news_list_url").toUrl());

    news_layout = new QVBoxLayout(this);
    news_layout->setSpacing(10);
    news_layout->setObjectName(QStringLiteral("news_layout"));
    news_layout->setContentsMargins(2, 2, 10, 2);
    news_layout->setSizeConstraint(QLayout::SetNoConstraint);
    connect(&news_update_timer, &QTimer::timeout, &news_downloader, &Downloader::start);
    connect(&news_downloader, &Downloader::downloadFinished, this, &NewsListWidget::updateNews);
    news_downloader.start();
    news_update_timer.setInterval(1000 * 60 * 5); //  5 minutes;
    news_update_timer.start();

    setMouseTracking(true);
}

NewsListWidget::~NewsListWidget()
{
    news_update_timer.stop();
}

void NewsListWidget::leaveEvent(QEvent *event)
{
    emit showNoToolTip();
}

void NewsListWidget::enterEvent(QEvent *event)
{
    emit showHelpToolTip();
}

void NewsListWidget::updateNews()
{
    if (!qApp)
        return;

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

    QStringList news_list = QString(news_data).split(":::");
    news_data.clear();

    for (int i = 0; i < news_list.size(); i++) {
        QStringList news_piece = news_list[i].split("|");

        if (news_piece.size() != 5) {
            qDebug() << "Incorrect news piece: " << news_piece << "\nNews data:" << news_list;
            return;
        }

        QString img_src = news_piece[0];
        QString news_title = news_piece[1];
        QString news_desrc = news_piece[2];
        QString news_src = news_piece[3];
        QString news_date = news_piece[4];

        constructNewsPiece(i, news_title, news_desrc, news_src, news_date);
    }

    QSpacerItem* verticalSpacer = new QSpacerItem(20, 0, QSizePolicy::Minimum, QSizePolicy::Expanding);
    news_layout->addItem(verticalSpacer);
}

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

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

    NewsPiece* news_piece = new NewsPiece(this);
    news_piece->setObjectName(QStringLiteral("news_piece_") + QString::number(piece_id));
    news_piece->setTitle(title, news_src);
    news_piece->setDate(news_date);

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