#include "request_opts.h"
#include <util/string/type.h>

TRequestOptions::TRequestOptions()
{

}

void TRequestOptions::Parse(const TServerRequestData& rd) {
    ParseTrace(rd);
    ParseVerboseLogging(rd);
    ParseWaitReply(rd);
    ParseRealtime(rd);
    ParseTimeout(rd);
    ParseAllowedBackends(rd);
    ParseAuthCookie(rd);
    ParseSource(rd);
    ParseBypassDistributor(rd);
    ParseSizeLimit(rd);
    ParseIndexSleep(rd);
    ParseInstantReply(rd);
}

void TRequestOptions::ParseTrace(const TServerRequestData& rd) {
    ReadCgiParam(rd, "trace", Trace);
}

void TRequestOptions::ParseVerboseLogging(const TServerRequestData& rd) {
    if (ReadCgiParam(rd, "ftests", VerboseLogging))
        return;
    if (ReadCgiParam(rd, "debug", VerboseLogging))
        return;
}

void TRequestOptions::ParseWaitReply(const TServerRequestData& rd) {
    ReadCgiParam(rd, "wait_reply", WaitReply);
}

void TRequestOptions::ParseRealtime(const TServerRequestData& rd) {
    HasRealtimeFlag = ReadCgiParam(rd, "realtime", Realtime);
}

void TRequestOptions::ParseInstantReply(const TServerRequestData& rd) {
    ReadCgiParam(rd, "instant_reply", InstantReply);
}

void TRequestOptions::ParseTimeout(const TServerRequestData& rd) {
    ui32 milliseconds;
    if (ReadCgiParam(rd, "timeout", milliseconds)) {
        Timeout = TDuration::MilliSeconds(milliseconds);
    }
}

void TRequestOptions::ParseIndexSleep(const TServerRequestData& rd) {
    const TString& string = rd.CgiParam.Get("index_sleep");
    if (string)
        IndexSleep = TDuration::Parse(string);
    else
        IndexSleep = TDuration::Zero();
}

void TRequestOptions::ParseAllowedBackends(const TServerRequestData& rd) {
    AllowedBackends.clear();
    std::pair<TCgiParameters::const_iterator, TCgiParameters::const_iterator> range(rd.CgiParam.equal_range("allowed_backend"));
    for(TCgiParameters::const_iterator i = range.first; i != range.second; ++i) {
        AllowedBackends.insert(i->second);
    }

    TryFromString<bool>(rd.CgiParam.Get("disable_queue"), DisableQueue);
}

void TRequestOptions::ParseAuthCookie(const TServerRequestData& rd) {
    AuthCookie = rd.CgiParam.Get("auth");
}

void TRequestOptions::ParseBypassDistributor(const TServerRequestData& rd) {
    ReadCgiParam(rd, "direct", BypassDistributor);
}

void TRequestOptions::ParseSizeLimit(const TServerRequestData& rd) {
    ReadCgiParam(rd, "size_limit", SizeLimit);
}

void TRequestOptions::ParseSource(const TServerRequestData& rd) {
    Source = rd.CgiParam.Get("source");
    if (!Source) {
        Source = "default";
    }
}
