#include "gui\newswidget.h"
#include "ui_newswidget.h"

#include "networkdownloader.h"
#include "legacyapp.h"
#include <QtConcurrent/QtConcurrent>
#include <QLabel>

NewsWidget::NewsWidget(LegacyApp *_app, QWidget *parent) :
    QWidget(parent),
    ui(new Ui::NewsWidget),
    app(_app), news_downloader(this)
{
    ui->setupUi(this);
    ui->test_news_piece->hide();

    news_downloader.targetBytearray = &news_data;
    news_downloader.setUrl(QUrl("http://translate.lotros.ru/groupware/launcher_news"));

    connect(&news_update_timer, &QTimer::timeout, &news_downloader, &NetworkDownloader::start);
    connect(&news_downloader, &NetworkDownloader::downloadFinished, this, &NewsWidget::updateNews);
    emit news_downloader.start();
    news_update_timer.setInterval(1000 * 60); // 10 minutes;
    news_update_timer.start();
}

NewsWidget::~NewsWidget()
{
    news_update_timer.stop();
    delete ui;
}

void NewsWidget::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("|");

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

        constructNewsPiece(i, news_title, news_desrc, news_src);

        QtConcurrent::run([i, this, img_src](){
            NetworkDownloader img_dwnld;
            QByteArray img;
            img_dwnld.setUrl(QUrl(img_src));
            img_dwnld.targetBytearray = &img;
            img_dwnld.start();
            img_dwnld.waitForDownloaded();
            QPixmap img_pixmap;
            img_pixmap.loadFromData(img);
            setImgToNewsPiece(i, img_pixmap);
        });
    }

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

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

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

    QWidget* news_piece = new QWidget(this);

    news_piece->setObjectName(QStringLiteral("news_piece_") + QString::number(piece_id));
    QSizePolicy sizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed);
    sizePolicy.setHorizontalStretch(0);
    sizePolicy.setVerticalStretch(0);
    sizePolicy.setHeightForWidth(news_piece->sizePolicy().hasHeightForWidth());

    news_piece->setSizePolicy(sizePolicy);
    news_piece->setStyleSheet(QLatin1String("QWidget{\n"
                                            "border-radius: 20px;\n"
                                            "background-color: rgba(30, 0, 0, 100);\n"
                                            "color: white;\n"
                                            "}\n"
                                            "\n"
                                            "QLabel{\n"
                                            "border-radius: 2px;\n"
                                            "background-color:rgba(0,0,0,0);\n"
                                            "}"));

    QGridLayout* news_piece_layout = new QGridLayout(news_piece);
    news_piece_layout->setObjectName(QStringLiteral("news_piece_layout"));
    news_piece_layout->setContentsMargins(11, 11, 11, 11);
    news_piece_layout->setSpacing(15);

    QLabel* iconLabel = new QLabel(news_piece);
    iconLabel->setObjectName(QStringLiteral("news_icon_") + QString::number(piece_id));
    QSizePolicy sizePolicy1(QSizePolicy::Fixed, QSizePolicy::Fixed);
    sizePolicy1.setHorizontalStretch(0);
    sizePolicy1.setVerticalStretch(0);
    sizePolicy1.setHeightForWidth(iconLabel->sizePolicy().hasHeightForWidth());

    iconLabel->setSizePolicy(sizePolicy1);
    iconLabel->setMinimumSize(QSize(60, 60));
    iconLabel->setMaximumSize(QSize(60, 60));
    iconLabel->setPixmap(QPixmap(QString::fromUtf8(":/assets/appicon.ico")).scaled(60, 60));

    iconLabel->setStyleSheet("border-radius: 10px;");

    news_piece_layout->addWidget(iconLabel, 0, 0, 2, 1);

    QLabel* titleLabel = new QLabel(news_piece);
    titleLabel->setObjectName(QStringLiteral("titleLabel_title"));
    sizePolicy.setHeightForWidth(titleLabel->sizePolicy().hasHeightForWidth());
    titleLabel->setSizePolicy(sizePolicy);

    QFont font;
    font.setFamily(QStringLiteral("Trajan Pro 3"));
    font.setPixelSize(12);
    font.setBold(false);
    font.setUnderline(false);

    titleLabel->setFont(font);
    titleLabel->setAlignment(Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter);
    titleLabel->setWordWrap(true);
    titleLabel->setText("<a style=\"color: #cfa644; text-decoration:none;\" href = '" + news_src + "'>" + title + "</a>");
    titleLabel->setOpenExternalLinks(true);

    news_piece_layout->addWidget(titleLabel, 0, 1, 1, 1);

    QLabel* contentLabel = new QLabel(news_piece);
    contentLabel->setObjectName(QStringLiteral("contentLabel_common"));
    contentLabel->setAlignment(Qt::AlignLeading|Qt::AlignLeft|Qt::AlignTop);
    contentLabel->setWordWrap(true);
    contentLabel->setText(text);
    contentLabel->setSizePolicy(sizePolicy);

    news_piece_layout->addWidget(contentLabel, 1, 1, 1, 1);
    app->window.changeFontSizeRecursive(app->properties.value("settings/ui_scale", 100).toInt(), news_piece);

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

void NewsWidget::setImgToNewsPiece(int piece_id, QPixmap img)
{
    QLabel* old_piece = findChild<QLabel*>("news_icon_" + QString::number(piece_id));
    if (!old_piece)
        return;
    old_piece->setPixmap(img.scaled(60, 60));
}
