#include "tile/init/override_flag.h"
#include "gflags/gflags.h"

#include <unordered_map>
#include <utility>

#include "tile/base/logging.h"

namespace tile {
namespace detail {
namespace {
using Registry = std::unordered_map<std::string, std::pair<std::string, bool>>;

Registry *
GetRegistry()
{
    static Registry registry;
    return &registry;
}
}// namespace

void
RegisterFlagOverrider(const std::string &name, const std::string &to, bool forcibly)
{
    auto &&value = (*GetRegistry())[name];
    if (!value.first.empty()) {
        TILE_LOG_FATAL("Duplicate override for flag {}, was [{}], now [{}]", name, value.first, to);
    }

    value = std::make_pair(to, forcibly);
}

void
ApplyFlagOverrider()
{
    for (auto &&item : *GetRegistry()) {
        auto &k      = item.first;
        auto &v      = item.second;

        auto current = gflags::GetCommandLineFlagInfoOrDie(k.c_str());
        if (current.is_default || v.second) {
            gflags::SetCommandLineOption(k.c_str(), v.first.c_str());
            TILE_VLOG(10, "Overriding flag [{}] with [{}]", k, v.first);
        }
    }
}

}// namespace detail
}// namespace tile
