#include "hashcomparer.h"

#include <QCoreApplication>
#include <updatenotifywidget.h>


HashComparer::HashComparer(DataParser *dataParser,QObject *)
{
    this->dataParser = dataParser;
}

void HashComparer::initialize(MainWindow* mainWindow)
{
    connect(this,&HashComparer::sigCallCheck,mainWindow,&MainWindow::checkUpdate);
    connect(this,&HashComparer::sigHaveDelta,mainWindow,&MainWindow::showUpdateInfo);
}

void HashComparer::CompareDeltas()
{
    QList<FileData> *serverStreamingHash = new QList<FileData>;
    QList<FileData> *localStreamingHash = new QList<FileData>;
    QList<FileData> *files = new QList<FileData>;

    QFile file(serverHash);
    file.open(QIODevice::ReadOnly | QIODevice::Text);

    serverStreamingHash = dataParser->xmlFileDataParse(file.readAll(),"StreamingAssets");
    file.close();

    QFile file2(streamingHashFilename);
    file2.open(QIODevice::ReadOnly | QIODevice::Text);

    localStreamingHash = dataParser->xmlFileDataParse(file2.readAll(),"StreamingAssets");
    file2.close();

    QMutableListIterator<FileData> iterator(*localStreamingHash);

    for (auto &item:*localStreamingHash)
    {
        if(!serverStreamingHash->contains(item))
        {
            files->append(item);
        }
    }

    filesForUpdate = files;
    showDeltas();
}

void HashComparer::showDeltas()
{

    if (filesForUpdate->length() <= 0)
    {
        emit sigCallCheck();
        return;
    }
    for (auto &item:*filesForUpdate)
    {
        updateWidget->addToList(item);
    }

    emit sigHaveDelta();
}

void HashComparer::setWidget(UpdateNotifyWidget* updateWidget)
{
    this->updateWidget = updateWidget;
}

QList<FileData> *HashComparer::getFilesForUpdate() const
{
    return filesForUpdate;
}

HashComparer::~HashComparer()
{

}
