#include "gui\rusificationwidget.h"
#include "ui_rusificationwidget.h"
#include "legacyapp.h"
#include "rusificationtreeitem.h"

void doStuffWithEveryItemInMyTree( QTreeWidgetItem *item )
{
    item->setCheckState(0, Qt::Checked);
    for( int i = 0; i < item->childCount(); ++i )
        doStuffWithEveryItemInMyTree( item->child(i) );
}

QTreeWidgetItem* findItemByName(QTreeWidgetItem* item, QString name) {
    for (int i = 0; i < item->childCount(); i++) {
        if (((RusificationTreeItem*)item->child(i))->name == name)
            return item->child(i);

        QTreeWidgetItem* found_item = findItemByName(item->child(i), name);
        if (found_item)
            return found_item;
    }
    return nullptr;
}

RusificationWidget::RusificationWidget(LegacyApp *_app, QWidget *parent) :
    QWidget(parent),
    ui(new Ui::RusificationWidget),
    app(_app)
{
    ui->setupUi(this);
    setupTreeWidget();

    ui_update_timer.setInterval(500);
    connect(&ui_update_timer, &QTimer::timeout, this, &RusificationWidget::updateUI);
    ui_update_timer.start();
}

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

void RusificationWidget::setupTreeWidget()
{
    connect(ui->treeWidget_title, &QTreeWidget::itemEntered, this, &RusificationWidget::onHoveredTreeItemChanged);

    QSettings patch_list(qApp->applicationDirPath() + "/legacy_patches.ini", QSettings::IniFormat);
    patch_list.setIniCodec("UTF-8");
    ui->treeWidget_title->setMouseTracking(true);

    foreach (const QString &group, patch_list.childGroups()) {
        qDebug() << "Processing " << group << " patch item";

        RusificationTreeItem* item = new RusificationTreeItem(group);
        item->parseSettingsItem(patch_list);

        QTreeWidgetItem* parent_item = findItemByName(ui->treeWidget_title->invisibleRootItem(), item->parent_name);
        if (!parent_item)
            parent_item = ui->treeWidget_title->invisibleRootItem();

        parent_item->addChild(item);
    }

    ui->treeWidget_title->expandAll();
    doStuffWithEveryItemInMyTree(ui->treeWidget_title->invisibleRootItem());
}

void RusificationWidget::onHoveredTreeItemChanged(QTreeWidgetItem *item, int column)
{
    RusificationTreeItem *tree_item = (RusificationTreeItem*)(item);
    ui->patch_hint->setText("Патч: " + tree_item->title + "\nОписание: " + tree_item->description);
}

void RusificationWidget::updateUI()
{
    if (!qApp)
        return;

    QPoint pos = QCursor::pos();
    QWidget *hovered = qApp->widgetAt(pos);
    if (!hovered) {
        ui->patch_hint->setText("No object!");
    }

    if (hovered) {
        QWidget* parent = hovered->parentWidget();
        if (parent && (hovered->objectName() != "qt_scrollarea_viewport"
                       || parent->objectName() != "treeWidget_title"))
            ui->patch_hint->setText(hovered->objectName() + "\n" + parent->objectName());
    }
}
