#include <stdio.h>

#include "ConfigPanel.h"
#include "LogConversionRunnable.h"
#include "usbtenki_version.h"

static void progress_callback(uint32_t done, uint32_t total, void *user_data) {

    LogConversionRunnable *r = (LogConversionRunnable *)user_data;
    emit r->progress(done, total);
}

LogConversionRunnable::LogConversionRunnable(const QString &inputPath, const QString &outputPath)
    : inputPath(inputPath), outputPath(outputPath), csvopt(ConfigPanel::instance().getCSVOptions()) {}

LogConversionRunnable::~LogConversionRunnable() {}

void LogConversionRunnable::run() {

    QByteArray outputPathByteArray = outputPath.toLocal8Bit();

    FILE *output = fopen(outputPathByteArray.data(), "w");
    if (!output) {
        emit error(ERROR_OPEN_OUTPUT);
        return;
    }

    QByteArray inputPathByteArray = inputPath.toLocal8Bit();

    DataLog *datalog = datalog_open_read(inputPathByteArray.data());
    if (!datalog) {
        fclose(output);
        emit error(ERROR_OPEN_INPUT);
        return;
    }

    csvopt.file = output;
    csvopt.datalog = datalog;

    CSV csv = csv_init(&csvopt);
    csv_convert(csv, 1, -1, progress_callback, this);
    csv_exit(csv);

    fclose(output);
    datalog_close(datalog);
}
