#include "task_params.h"

#include <maps/libs/enum_io/include/enum_io.h>
#include <maps/libs/log8/include/log8.h>

#include <map>

namespace maps::wiki::exporter {

TaskParams::TaskParams(const grinder::worker::Task& task)
    : grinderTask(&task)
{
    const auto& args = task.args();
    taskId = args["taskId"].as<uint64_t>();
    commitId = args["commitId"].as<revision::DBID>();
    branch = args["branch"].as<std::string>();
    subset = enum_io::fromString<Subset>(args["subset"].as<std::string>());
    experiment = args["experiment"].as<std::string>();
    tested = args["tested"].as<bool>() ? IsTested::Yes : IsTested::No;
}


TaskParams::TaskParams(
        uint64_t taskId_,
        revision::DBID commitId_,
        const std::string& branch_,
        Subset subset_,
        const std::string& experiment_,
        IsTested tested_)
    : grinderTask(nullptr)
    , taskId(taskId_)
    , commitId(commitId_)
    , branch(branch_)
    , subset(subset_)
    , experiment(experiment_)
    , tested(tested_)
{}

std::string makeTaskTag(
    uint64_t taskId,
    const std::string& branch,
    revision::DBID commitId)
{
    constexpr size_t BUF_LEN = 80;
    char buf[BUF_LEN];
    time_t rawtime;
    ::time(&rawtime);
    struct tm tmRes;
    ::localtime_r(&rawtime, &tmRes);
    auto sz = ::strftime(buf, BUF_LEN, DATE_FORMAT.c_str(), &tmRes);
    REQUIRE(sz > 0, "Failed to format timestamp");

    auto numBytes = snprintf(buf + sz, BUF_LEN - sz,
            TASK_TAG_PATTERN.c_str(), taskId, branch.data(), commitId);
    REQUIRE(numBytes > 0 && sz + numBytes < BUF_LEN,
            "Failed to generate unique task tag");

    return std::string(buf);
}

std::string makeTaskTag(const TaskParams& taskParams)
{
    return makeTaskTag(taskParams.taskId, taskParams.branch, taskParams.commitId);
}

void checkCanceled(const TaskParams& taskParams)
{
    if (taskParams.grinderTask && taskParams.grinderTask->isCanceled()) {
        WARN() << "Export canceled";
        throw ExportCanceledException();
    }
}

} // namespace maps::wiki::exporter
