#include <saas/library/persqueue/writer/writer.h>
#include <saas/library/persqueue/logger/logger.h>

#include <util/system/env.h>

int main() {
    TLog logger("logbroker.log");
    THolder<NSaas::TPersQueueWriter> writer;
    TIntrusivePtr<NPersQueue::ILogger> loggerPtr = new NSaas::TPersQueueLogger<NPersQueue::ILogger>(logger);

    TString serviceName = "ad_moderation";
    TString servcieCtype = "prestable";
    TString directoryWithTopics = "saas/services/" + serviceName + "/" + servcieCtype + "/topics";

    NSaas::TSearchMapInputSettings searchMapSettings;
    searchMapSettings.DMHost = "saas-dm-proxy.n.yandex-team.ru";
    searchMapSettings.StaticaHost = "saas-searchmap.s3.mds.yandex.net"; // mds - standby receiving source
    searchMapSettings.StaticaQuery = servcieCtype;
    searchMapSettings.Ctype = servcieCtype;

    auto srcTvmClientId = FromString<NTvmAuth::TTvmId>(GetEnv("TVM_CLIENT_ID"));
    TString srcTvmSecret = GetEnv("TVM_SECRET");

    NTvmAuth::TTvmId logbrokerTvmClientId = 2001059;

    do {
        NSaas::TPersQueueWriterSettings settings;
        writer.Reset(new NSaas::TPersQueueWriter());
        try {
            settings.SetLogger(loggerPtr)
                .SetServiceInfo(searchMapSettings, serviceName)
                .SetTvm(srcTvmClientId, logbrokerTvmClientId, srcTvmSecret)
                .SetPersQueueSettings("logbroker.yandex.net", directoryWithTopics);
            writer->Init(settings);
        } catch(...) {
            Cerr << "Error in creating: " << CurrentExceptionMessage() << Endl;
            writer.Reset(nullptr);
        }
    } while(!writer);

    NSaas::TAction action;
    action.SetActionType(NSaas::TAction::atDelete);
    auto& doc = action.AddDocument();
    doc.SetUrl("fakeurl");

    TToJsonContext context(TToJsonContext::COMMON_JSON);
    NJson::TJsonValue jsonMessage = action.ToJson(context);

    NRTYServer::TMessage protoMessage = action.ToProtobuf();

    Cerr << "Write TAction: " << writer->Write(action).GetValueSync().ToString() << Endl;
    Cerr << "Write json: " << writer->Write(jsonMessage).GetValueSync().ToString() << Endl;
    Cerr << "Write proto TMessage:" << writer->Write(protoMessage).GetValueSync().ToString() << Endl;
    return 0;
}
