#include "fasthashcalculator.h"
#include <QtConcurrent>


FastHashCalculator::FastHashCalculator(QObject *parent) : QObject(parent)
{
    hashList = new QList<FileData>();
}
void FastHashCalculator::calculateHashes(QString path)
{
    hashList->clear();

    if(!QDir(path).exists()){
        QDir().mkdir(path);
    }

    QString hashString;
    QStringList filter;
    filter << "*";
    QList<FileData> *folders = new QList<FileData>;

    QDirIterator dirIterator(path,filter, QDir::AllEntries, QDirIterator::Subdirectories);

    while (dirIterator.hasNext())
    {
        QFileInfo fileInfo(dirIterator.next());
        FileData currentFolder;
        if(fileInfo.isDir() && !fileInfo.fileName().startsWith(".") && fileInfo.fileName() != projectFolderName)
        {
            currentFolder.path = Tools::createLocalPath(fileInfo.absoluteFilePath());
            currentFolder.hash = "FOLDER";

            if(!folders->contains(currentFolder))
            {
                folders->push_back(currentFolder);
            }
        }
    }

    hashList->append(*folders);

    QDirIterator fileIterator(path,filter,QDir::Files | QDir::NoDotAndDotDot,QDirIterator::Subdirectories);

    QList<QString> files;
    files.clear();

    while(fileIterator.hasNext())
    {
        fileIterator.next();
        QFileInfo fileInfo = fileIterator.fileInfo();
        QString path = fileInfo.absoluteFilePath();

        //фильтры
        if (fileInfo.isHidden()) continue;
        if (!fileInfo.isFile()) continue;
        if (fileInfo.fileName().contains(".meta")) continue;
        if (fileInfo.fileName() == "docs.xml") continue;

        files.append(path);
    }

    QtConcurrent::map(files, [this](const QString &filePath)
    {
        QByteArray hash = calculateFileHashOptimized(filePath);
        QMutexLocker locker(&_mutex);
        FileData currentFile;
        QString hashName;

        currentFile.path = Tools::createLocalPath(filePath);
        currentFile.hash = hash.toHex();
        hashList->append(currentFile);
     }).waitForFinished();

    emit finished();
}

QByteArray FastHashCalculator::calculateFileHashOptimized(const QString &filePath)
{
    QFile file(filePath);
            if (!file.open(QIODevice::ReadOnly)) return QByteArray();

            QCryptographicHash hash(QCryptographicHash::Md5);
            const qint64 bufferSize = 2 * 1024; // 2MB
            QByteArray buffer;
            buffer.resize(bufferSize);

            while (!file.atEnd()) {
                qint64 bytesRead = file.read(buffer.data(), bufferSize);
                hash.addData(buffer.constData(), bytesRead);
            }

            return hash.result();
}

QList<FileData> *FastHashCalculator::getHashList() const
{
    return hashList;
}
