/***************************** LICENSE START ***********************************

 Copyright 2014 ECMWF and INPE. This software is distributed under the terms
 of the Apache License version 2.0. In applying this license, ECMWF does not
 waive the privileges and immunities granted to it by virtue of its status as
 an Intergovernmental Organization or submit itself to any jurisdiction.

 ***************************** LICENSE END *************************************/

#include "MvQFind.h"

#include <QDebug>
#include <QFile>

#include "Path.h"

#include "FolderInfo.h"
#include "IconClass.h"

MvQFind::MvQFind(std::string mvRoot, QObject* parent) :
    QThread(parent),
    mvRoot_(mvRoot),
    abort_(false)
{
}

MvQFind::~MvQFind()
{
    mutex_.lock();
    abort_ = true;
    // condition.wakeOne();
    mutex_.unlock();

    wait();
}

void MvQFind::find(const std::string& dir, FindOptions options)
{
    options_ = options;
    path_ = dir;
    abort_ = false;
    start(LowPriority);
}

void MvQFind::abortFind()
{
    mutex_.lock();
    abort_ = true;
    mutex_.unlock();
}

void MvQFind::run()
{
    scan();
}

void MvQFind::scan()
{
    mutex_.lock();
    Path dir(this->path_);
    FindOptions options = this->options_;
    mutex_.unlock();

    // Get classes to be searched for
    std::vector<std::string> classes;

    if (options.strictType == false) {
        std::vector<const IconClass*> icVec;
        IconClass::find(options.type, icVec, false);
        if (!options.type.empty() && icVec.size() == 0)
            return;

        for (auto it : icVec) {
            classes.push_back(it->name());
        }
    }
    else {
        if (!options.type.empty()) {
            const IconClass& ic = IconClass::find(options.type);
            classes.push_back(ic.name());
        }
    }

    scan(dir, options, classes);
}


void MvQFind::scan(const Path& dir, const FindOptions& options, const std::vector<std::string>& classes)
{
    if (abort_)
        return;

    std::string dirName = dir.str();

    std::set<std::string> fs = dir.files();
    std::set<std::string> ds;

    std::map<std::string, std::string> icons;
    bool hasInfo = FolderInfo::read(dir, icons);

    for (const auto& f : fs) {
        std::string name, icName, icType;

        name = f;

        bool doMatch = true;

        // Check folders
        struct stat buf
        {
        };
        std::string fName = dirName + "/" + (name);

        bool needDir = false;

        // Check folders
        if (stat(fName.c_str(), &buf) >= 0) {
            if ((buf.st_mode & S_IFMT) == S_IFDIR) {
                // Ignore embedded folders - they end with #
                if (fName[fName.length() - 1] == '#') {
                    doMatch = false;
                }
                // Ignore links if options.followLinks==false
                else if (!options.followLinks &&
                         lstat(fName.c_str(), &buf) >= 0) {
                    if (S_ISLNK(buf.st_mode))
                        needDir = false;
                    else
                        needDir = true;
                }
                else
                    needDir = true;
            }
        }

        if (doMatch) {
            if (hasInfo) {
                auto itC = icons.find(name);
                if (itC != icons.end()) {
                    icName = itC->second;
                }
            }

            if (match(options, dir.str(), name, classes, icName, icType))
                emit found(QString::fromStdString(dir.add(name).str()),
                           QString::fromStdString(icName));
        }

        if (needDir && icName != "ODB_DB") {
            ds.insert(name);
        }
    }

    if (options.includeSub) {
        for (const auto& d : ds) {
            Path p(dir.add(d));
            scan(p, options, classes);
        }
    }
}

bool MvQFind::match(const FindOptions& options, const std::string& fileDir, const std::string fileName,
                    const std::vector<std::string>& classes, std::string& icName, std::string& icType)
{
    bool hasOption = false;
    std::string fullName = fileDir + "/" + fileName;

    // Check name
    if (!options.name.empty()) {
        hasOption = true;
        QString fileNameStr = QString::fromStdString(fileName);
        if (!fileNameStr.contains(QString::fromStdString(options.name), Qt::CaseInsensitive)) {
            return false;
        }
    }

    Path path(fullName);

    // Check timestamp
    if (options.useTime) {
        hasOption = true;
        time_t modTime = path.lastModified();
        if (modTime < options.fromTime || modTime > options.toTime)
            return false;
    }

    // Check size
    if (options.size > 0) {
        hasOption = true;
        off_t diff = path.sizeInBytes() - options.size;
        if (diff < 0 && options.sizeOper >= 0)
            return false;
        else if (diff > 0 && options.sizeOper <= 0)
            return false;
        else if (diff != 0 && options.sizeOper == 0)
            return false;
    }

    // Check owner
    if (!options.owner.empty()) {
        hasOption = true;
        if (path.owner() != options.owner)
            return false;
    }

    // Check group
    if (!options.group.empty()) {
        hasOption = true;
        if (path.group() != options.group)
            return false;
    }

    // Check type
    if (!options.type.empty()) {
        hasOption = true;
        if (icName.empty()) {
            IconClass::guess(fullName, icName, icType);
        }
        if (classes.size() > 0) {
            if (std::find(classes.begin(), classes.end(), icName) == classes.end()) {
                return false;
            }
        }
    }

    // Check contents
    if (!options.contentText.empty()) {
        hasOption = true;
        if (icType.empty()) {
            IconClass::guess(fullName, icName, icType);
        }

        QString fullNameStr = QString::fromStdString(fullName);

        if (isTextType(icName, icType)) {
            QFile file(fullNameStr);

            if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
                return false;

            QByteArray ba = file.readAll();
            QString con(ba);

            file.close();

            Qt::CaseSensitivity cs = (options.contentCaseSensitive) ? (Qt::CaseSensitive) : (Qt::CaseInsensitive);

            if (!con.contains(QString::fromStdString(options.contentText), cs))
                return false;
        }
        else
            return false;
    }

    if (icName.empty()) {
        IconClass::guess(fullName, icName, icType);
    }

    return (hasOption) ? true : false;
}

bool MvQFind::isTextType(const std::string& icName, const std::string& icType)
{
    return (icName != "FOLDER" &&
            (icType != "FILE" ||
             (icName == "SHELL" || icName == "NOTE" || icName == "SQL" ||
              icName == "KML" || icName == "NAMELIST" || icName == "GEOPOINTS" ||
              icName == "FLEXTRA_FILE" || icName == "MAGML" || icName == "VAPOR_VDF_FILE" ||
              icName == "LLMATRIX" || icName == "TABLE")));
}

void MvQFind::toRelPath(const std::string& path, std::string& relPath)
{
    QString sp = QString::fromStdString(path);
    sp.remove(QString::fromStdString(mvRoot_.str()));
    if (sp.isEmpty())
        sp = "/";
    relPath = sp.toStdString();
}
