#include <saas/common_proxy/lib/configs/sender.h>
#include <util/generic/yexception.h>
#include <util/string/vector.h>
#include <util/string/split.h>

void NCommonProxy::TSenderConfig::Init(const TYandexConfig::Section& section) {
    const TYandexConfig::Directives& dir = section.GetDirectives();
    if (!dir.GetValue("Host", Host))
        ythrow yexception() << "Cannot create Sender: set Host";
    if (!dir.GetValue("Port", Port))
        ythrow yexception() << "Cannot create Sender: set Port";
    Url = dir.Value("Url", TString());
    TString timeout = dir.Value("Timeout", TString("10s"));
    Timeout = TDuration::Parse(timeout);
    SendType = dir.Value("SendType", TString("json"));
    dir.GetValue("AttemptsCount", AttemptsCount);
    dir.GetValue("AsyncSendThreads", AsyncSendThreads);
    dir.GetValue("MaxInFly", MaxInFly);
    SendParams.Realtime = dir.Value("Realtime", true);
    SendParams.VerboseReply = dir.Value("VerboseReply", false);
    TString resendDurations = dir.Value("ResendDurations", TString());
    ResendDurations.clear();
    for (const auto& dur : static_cast<TVector<TString>>(StringSplitter(resendDurations).SplitBySet(" ,").SkipEmpty())) {
        ResendDurations.push_back(TDuration::Parse(dur));
    }
}

void NCommonProxy::TSenderConfig::ToString(IOutputStream& so) const {
    so << "Host: " << Host << Endl;
    so << "Port: " << Port << Endl;
    so << "Url: " << Url << Endl;
    so << "Timeout: " << Timeout.ToString() << Endl;
    so << "SendType: " << SendType << Endl;
    so << "InstantReply: " << SendParams.InstantReply << Endl;
    so << "VerboseReply: " << SendParams.VerboseReply << Endl;
    so << "AttemptsCount: " << AttemptsCount << Endl;
    so << "AsyncSendThreads: " << AsyncSendThreads << Endl;
    so << "MaxInFly: " << MaxInFly << Endl;
    TVector<TString> durations;
    for (TDuration dur : ResendDurations) {
        durations.push_back(dur.ToString());
    }
    so << "ResendDurations: " << JoinStrings(durations, ",") << Endl;
}
