#include "command_line_trace_cleaner.h"
#include <unistd.h>
#include <pwd.h>
#include <fstream>
#include <string>
#include <QDebug>
#include <QFile>

namespace junk_clean {

CommandLineTraceCleaner::CommandLineTraceCleaner(QObject *parent)
    : Cleaner(parent),
      bash_history_file_("")
{
    struct passwd *pw = getpwuid(getuid());
    if (pw) {
        if (pw->pw_dir) {
            bash_history_file_ = QString("%1/.bash_history").arg(pw->pw_dir);
        } else {
            qCritical() << "Command line trace get home dir fail.";
        }
    } else {
        qCritical() << "Command line trace get pw info fail: " << strerror(errno);
    }
}

QString CommandLineTraceCleaner::Mark() const {
    return "command_line_trace_cleaner";
}

enum Type CommandLineTraceCleaner::Type() const {
    return Type::kUsageTraces;
}

enum Level CommandLineTraceCleaner::Level() const {
    return Level::kNoEffect;
}

QString CommandLineTraceCleaner::Name() const {
    return tr("Command line history");
}

QString CommandLineTraceCleaner::Description() const {
    return tr("Historical traces generated by using the command line");
}

void CommandLineTraceCleaner::Scan() {
    quint64 total_size{0};

    do {
        if (bash_history_file_.isEmpty()) {
            qCritical() << "Command line trace scan get record file path fail.";
            break;
        }
        std::ifstream ifs(bash_history_file_.toStdString(), std::ios::in);
        if (!ifs.is_open()) {
            qCritical() << "Command line trace scan open record file fail.";
            break;
        }
        std::string line;
        while (std::getline(ifs, line)) {
            total_size++;
        }
        ifs.close();
    } while (0);

    Q_EMIT sig_ScanFinish(Mark(), total_size);
}

void CommandLineTraceCleaner::Clean([[maybe_unused]]QList<quint64> junk_marks) {
    do {
        if (bash_history_file_.isEmpty()) {
            qCritical() << "Command line trace clean get record file path fail.";
            break;
        }
        QFile file(bash_history_file_);
        if (file.exists()) {
            if (!QFile::remove(bash_history_file_)) {
                qCritical() << "Command line trace clean record file fail.";
            }
        }
    } while (0);

    Q_EMIT sig_CleanFinish(Mark());
}

}
