#include "zonefileviewer.h"
#include "ui_zonefileviewer.h"

#include "statusbarmanager.h"

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

    mZoneFile = nullptr;

    ui->tableWidget_RecordCounts->setColumnCount(3);
    ui->tableWidget_RecordCounts->setHorizontalHeaderLabels({ "Identifier", "Asset", "Count" });
    ui->tableWidget_RecordCounts->horizontalHeader()->setStretchLastSection(true);

    ui->tableWidget_RecordOrder->setColumnCount(3);
    ui->tableWidget_RecordOrder->setHorizontalHeaderLabels({ "Identifier", "Asset", "Count" });
    ui->tableWidget_RecordOrder->horizontalHeader()->setStretchLastSection(true);

    connect(ui->lineEdit_TagSearch, &QLineEdit::textChanged, this, &ZoneFileViewer::SortTags);
    connect(ui->tableWidget_RecordCounts, &QTableWidget::itemSelectionChanged, this, &ZoneFileViewer::HighlightRecordInOrder);
    connect(ui->listWidget_Tags, &QListWidget::currentTextChanged, this, [this](const QString &aCurrentText) {
        StatusBarManager::instance().updateStatus(QString("Selected tag '%1' with index %2").arg(aCurrentText).arg(mZoneFile->GetTags().indexOf(aCurrentText)));
    });
}

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

void ZoneFileViewer::HighlightRecordInOrder() {
    ui->tableWidget_RecordOrder->clearSelection();

    foreach (auto selectedItem, ui->tableWidget_RecordCounts->selectedItems()) {
        int selectedRow = selectedItem->row();
        const QString assetId = ui->tableWidget_RecordCounts->item(selectedRow, 0)->text();

        for (int i = 0; i < ui->tableWidget_RecordOrder->rowCount(); i++) {
            const QString testAssetId = ui->tableWidget_RecordOrder->item(i, 0)->text();
            if (testAssetId != assetId) { continue; }

            ui->tableWidget_RecordOrder->selectRow(i);
            ui->tableWidget_RecordOrder->item(i, 0)->setSelected(true);
            ui->tableWidget_RecordOrder->item(i, 1)->setSelected(true);
            ui->tableWidget_RecordOrder->item(i, 2)->setSelected(true);
            ui->tableWidget_RecordOrder->item(i, 3)->setSelected(true);
        }
    }
}

void ZoneFileViewer::SortTags(const QString &aSearchText) {
    ui->listWidget_Tags->clear();

    const QStringList tags = mZoneFile->GetTags();
    if (aSearchText.isEmpty()) {
        ui->listWidget_Tags->addItems(tags);
        return;
    }

    QStringList sortedTags;
    foreach (const QString tag, tags) {
        if (tag.contains(aSearchText)) {
            sortedTags << tag;
        }
    }

    StatusBarManager::instance().updateStatus(QString("Found %1 tags.").arg(sortedTags.size()));
    ui->listWidget_Tags->addItems(sortedTags);
}

void ZoneFileViewer::SetZoneFile(const ZoneFile* aZoneFile) {
    mZoneFile = aZoneFile;

    ui->tableWidget_RecordCounts->clearContents();
    ui->tableWidget_RecordOrder->clearContents();
    ui->listWidget_Tags->clear();

    const QStringList tags = mZoneFile->GetTags();
    ui->listWidget_Tags->addItems(tags);
    ui->label_Title->setText(mZoneFile->GetBaseStem() + ".zone");

    ui->groupBox_Tags->setTitle(QString("Tags (%1)").arg(tags.size()));

    if (tags.isEmpty()) {
        ui->groupBox_Tags->hide();
    } else {
        ui->groupBox_Tags->show();
    }

    QMap<XAssetType, int> recordCounts = QMap<XAssetType, int>();
    QVector<QPair<XAssetType, int>> assetOccurances = QVector<QPair<XAssetType, int>>();
    for (XAssetType type : mZoneFile->GetTypes()) {
        if (!recordCounts.contains(type)) {
            recordCounts[type] = 0;
        }
        recordCounts[type]++;

        if (!assetOccurances.isEmpty() && assetOccurances.last().first == type) {
            assetOccurances.last().second++;
            continue;
        }

        QPair<XAssetType, int> assetOccurance(type, 1);
        assetOccurances << assetOccurance;
    }
    ui->tableWidget_RecordOrder->setRowCount(assetOccurances.size());

    int assetIndex = 0;
    foreach (auto assetOccurance, assetOccurances) {
        XAssetType assetType = assetOccurance.first;
        int assetCount = assetOccurance.second;

        QIcon assetIcon = Utils::CreateAssetIcon(assetType);
        if (assetIcon.isNull()) {
            qDebug() << "Icon is null for record: " << assetType;
        }

        QTableWidgetItem *recordItem = new QTableWidgetItem(QString::number(assetType, 16));
        QTableWidgetItem *recordStrItem = new QTableWidgetItem(XAsset::XAssetTypeToString(assetType));
        QTableWidgetItem *recordCountItem = new QTableWidgetItem(QString::number(assetCount));
        recordItem->setIcon(assetIcon);

        ui->tableWidget_RecordOrder->setItem(assetIndex, 0, recordItem);
        ui->tableWidget_RecordOrder->setItem(assetIndex, 1, recordStrItem);
        ui->tableWidget_RecordOrder->setItem(assetIndex, 2, recordCountItem);

        assetIndex++;
    }

    int recordIndex = 0;
    for (XAssetType assetType : recordCounts.keys()) {
        int recordCount = recordCounts[assetType];

        QIcon assetIcon = Utils::CreateAssetIcon(assetType);
        if (assetIcon.isNull()) {
            qDebug() << "Icon is null for record: " << assetType;
        }

        ui->tableWidget_RecordCounts->setRowCount(recordIndex + 1);

        QTableWidgetItem *recordItem = new QTableWidgetItem(QString::number(assetType, 16));
        QTableWidgetItem *recordCountStrItem = new QTableWidgetItem(XAsset::XAssetTypeToString(assetType));
        QTableWidgetItem *recordCountItem = new QTableWidgetItem(QString::number(recordCount));
        recordItem->setIcon(assetIcon);

        ui->tableWidget_RecordCounts->setItem(recordIndex, 0, recordItem);
        ui->tableWidget_RecordCounts->setItem(recordIndex, 1, recordCountStrItem);
        ui->tableWidget_RecordCounts->setItem(recordIndex, 2, recordCountItem);

        recordIndex++;
    }

    ui->tableWidget_RecordOrder->resizeColumnsToContents();
    ui->tableWidget_RecordCounts->resizeColumnsToContents();
}
