#include <library/cpp/getopt/small/last_getopt.h>
#include <library/cpp/svnversion/svnversion.h>
#include <util/datetime/base.h>
#include <util/stream/file.h>
#include <util/string/printf.h>

#include "args.h"
#include "config_base.h"

namespace NWebmaster {

bool TConfigBase::LogDisabled = false;

TConfigBase::TConfigBase()
    : GlobalOkFlag(false)
    , LocalOkFlag(false)
{
    GetRunTimestamp();
    LogDisabled = (getenv("CONFIG_DISABLE_LOG") != NULL);
}

void TConfigBase::Load() {
    TString &globalConfigPath = TArgs::Instance().GlobalConfigPath;
    TString &localConfigPath = TArgs::Instance().LocalConfigPath;

    try {
        TFileInput globalConfigFile(globalConfigPath);
        globalConfig = NConfig::TConfig::FromIni(globalConfigFile);
        LogInfo("Global config file <%s> sucessfully loaded", globalConfigPath.data());
        GlobalOkFlag = true;
    } catch(const std::exception &e) {
        LOG_ERROR("Unable to load global config file: %s", e.what());
    }

    try {
        TFileInput localConfigFile(localConfigPath);
        localConfig = NConfig::TConfig::FromIni(localConfigFile);
        LogInfo("Local config file <%s> sucessfully loaded", localConfigPath.data());
        LocalOkFlag = true;
    } catch(const std::exception &e) {
        LOG_WARN("Unable to load local config file: %s", e.what());
    }

    LogInfo("Timestamp <%s>", GetRunTimestamp().data());
}

bool TConfigBase::IsGlobalOk() const {
    return GlobalOkFlag;
}

bool TConfigBase::IsOk() const {
    return GlobalOkFlag && LocalOkFlag;
}

TString TConfigBase::GetProgramRevision() {
    static TString revision = "r" + ToString(GetProgramSvnRevision());
    return revision;
}

TString TConfigBase::GetFormatDate(const TString &format) {
    const struct tm *tm;
    time_t now = time(nullptr);
    tm = localtime(&now);
    return Strftime(format.data(), tm);
}

TString TConfigBase::GetRunTimestamp() {
    static TString ts = GetFormatDate("%s");
    return ts;
}

const TString TConfigBase::GetYTToken(const char *key) {
    char *token = getenv(key);
    if (token == nullptr) {
        ythrow yexception() << key << " env is not defined";
    }
    return token;
}

} //namespace NWebmaster
