#include "server.h"

#include <saas/rtyserver/common/common_messages.h>
#include <saas/rtyserver/common/message_collect_server_info.h>
#include <saas/rtyserver/config/config.h>
#include <saas/rtyserver/config/searcher_config.h>
#include <saas/rtyserver/config/realm_config.h>

#include <library/cpp/logger/global/global.h>

#include <util/stream/file.h>
#include <util/system/fs.h>

TDefaultKeyPrefix::TDefaultKeyPrefix(const NRTYServer::TSearcherConfig& config)
    : FileName(config.Owner.GetRealmListConfig().GetMainRealmConfig().RealmDirectory + "default.kps")
    , Prefix(0)
{
    TGuard<TMutex> g(Mutex);
    if (NFs::Exists(FileName)) {
        try {
            TUnbufferedFileInput fi(FileName);
            Prefix = FromString<ui64>(fi.ReadLine());
        } catch (const yexception& e) {
            ERROR_LOG << "Error while read " << FileName << ":" << e.what() << Endl;
        }
    }

    RegisterGlobalMessageProcessor(this);
}

TDefaultKeyPrefix::~TDefaultKeyPrefix() {
    UnregisterGlobalMessageProcessor(this);
}

void TDefaultKeyPrefix::Set(ui64 prefix) {
    TGuard<TMutex> g(Mutex);
    Prefix = prefix;
    TFixedBufferFileOutput fo(FileName);
    fo << Prefix;
}

bool TDefaultKeyPrefix::Process(IMessage* message) {
    if (auto messageSwitchKps = message->As<TMessageSwitchKps>()) {
        Set(messageSwitchKps->GetNewKps());
        return true;
    }

    if (auto messageCollect = message->As<TMessageCollectServerInfo>()) {
        messageCollect->SetDefaultKps(Get());
        return true;
    }

    return false;
}

TString TDefaultKeyPrefix::Name() const {
    return "DefaultKeyPrefix";
}
