#include "rty_search_context.h"

#include <saas/rtyserver/config/config.h>
#include <saas/util/logging/tskv_log.h>

#include <search/reqparam/reqparam.h>

TRTYSearchRequestContext::TRTYSearchRequestContext(const TCgiParameters& cgi, TRequestParams& rp, const TRTYServerConfig& serverConfig)
    : Cgi(cgi)
    , RP(rp)
    , Config(serverConfig)
{
    for (const auto& compSearch: Cgi.Range("comp_search")) {
        TComponentParameters comp;
        TString compName;
        if (Parse(compSearch, compName, comp)) {
            ParamsPerComponent[compName] = comp;
        }
    }
}

const TCgiParameters& TRTYSearchRequestContext::CgiParams() const {
    return Cgi;
}

const TRequestParams& TRTYSearchRequestContext::GetRP() const {
    return RP;
}

const TString& TRTYSearchRequestContext::GetComponentName() const {
    if (const TString& component = CgiParams().Get("component")) {
        return component;
    } else {
        return Config.IndexGenerator;
    }
}

const TMap<TString, TString>* TRTYSearchRequestContext::GetParameters(const TString& componentName) const {
    const auto it = ParamsPerComponent.find(componentName);
    if (it != ParamsPerComponent.end()) {
        return &it->second;
    }
    return nullptr;
}

bool TRTYSearchRequestContext::Parse(const TString& paramsStr, TString& componentName, TComponentParameters& parameters) const {
    if (paramsStr.empty())
        return false;

    NUtil::TTSKVRecordParser::Parse<';', ':'>(paramsStr, parameters);
    auto compIt = parameters.find("comp");

    if (compIt != parameters.end()) {
        componentName = compIt->second;
        return true;
    }

    return false;
}
