#include "log_cleaner.h"
#include <unistd.h>
#include <pwd.h>
#include <QDebug>
#include <QDir>
#include <QFileInfo>

namespace junk_clean {

LogCleaner::LogCleaner(QObject *parent)
    : Cleaner(parent),
      home_log_path_(""),
      total_size_(0),
      junk_mark_(0)
{
    struct passwd *pw = getpwuid(getuid());
    if (pw) {
        if (pw->pw_dir) {
            home_log_path_ = QString("%1/.log").arg(pw->pw_dir);
        } else {
            qCritical() << "Log cleaner get home path fail.";
        }
    } else {
        qCritical() << "Log cleaner get pw info fail.";
    }
}

QString LogCleaner::Mark() const {
    return "log_cleaner";
}

enum Type LogCleaner::Type() const {
    return Type::kSystemJunk;
}

enum Level LogCleaner::Level() const {
    return Level::kGeneral;
}

QString LogCleaner::Name() const {
    return tr("Log file");
}

QString LogCleaner::Description() const {
    return tr("Logs generated by software operation");
}

void LogCleaner::Scan() {
    log_junks_.clear();
    total_size_ = 0;
    junk_mark_ = 0;

    do {
        if (home_log_path_.isEmpty()) {
            qCritical() << "Log cleaner scan get scan path fail.";
            break;
        }
        RecursiveScanInDir(home_log_path_);
    } while (0);

    Q_EMIT sig_ScanFinish(Mark(), total_size_);
}

void LogCleaner::Clean(QList<quint64> junk_marks) {
    for (const auto &junk_mark: junk_marks) {
        auto iter = log_junks_.find(junk_mark);
        if (iter == log_junks_.end()) {
            qCritical() << "Log cleaner clean junk [" << junk_mark << "] is not exist.";
            Q_EMIT sig_CleanForJunk(Mark(), junk_mark);
            continue;
        }
        if (QFile::exists(iter.value())) {
            if (!QFile::remove(iter.value())) {
                qCritical() << "Log cleaner clean junk [" << iter.value() << "] fail.";
            }
        }
        log_junks_.erase(iter);
        Q_EMIT sig_CleanForJunk(Mark(), junk_mark);
    }
    Q_EMIT sig_CleanFinish(Mark());
}

void LogCleaner::RecursiveScanInDir(const QString &dir_path) {
    QDir dir(dir_path);
    if (!dir.exists()) {
        return;
    }

    auto entries = dir.entryList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot);
    for (const auto &entry: entries) {
        auto absolute_file_path = dir.absoluteFilePath(entry);
        QFileInfo file_info(absolute_file_path);
        if (file_info.isDir()) {
            RecursiveScanInDir(absolute_file_path);
        } else {
            JunkItem junk_item;
            junk_item.mark = ++junk_mark_;
            junk_item.path = absolute_file_path;
            junk_item.size = file_info.size();
            log_junks_.insert(junk_mark_, absolute_file_path);
            total_size_ += file_info.size();
            Q_EMIT sig_ScanForJunk(Mark(), junk_item);
        }
    }
}

}
