#include "search_config_builder_meta.h"
#include <saas/rtyserver/indexer_core/index_component_storage.h>
#include <saas/library/metasearch/helpers/rearrange.h>
#include <saas/rtyserver/config/config.h>
#include <saas/rtyserver/config/searcher_config.h>
#include <saas/rtyserver/config/shards_config.h>
#include <saas/rtyserver/config/realm_config.h>

TSearchConfigBuilderMeta::TSearchConfigBuilderMeta(const TRTYServerConfig& config)
    : TSearchConfigBuilder(config)
{}

TAutoPtr<TSearchConfig> TSearchConfigBuilderMeta::GetSearchConfig(const TPathName& dir) const {
    TAutoPtr<TSearchConfig> searchConfig;
    if (!!Config.GetSearcherConfig().DefaultConfigInstances[NRTYServer::TSearcherConfig::sctMeta])
        searchConfig.Reset(new TSearchConfig(*Config.GetSearcherConfig().DefaultConfigInstances[NRTYServer::TSearcherConfig::sctMeta].Get()));
    else
        searchConfig.Reset(new TSearchConfig);
    ApplyMainConfig(searchConfig.Get(), dir, NRTYServer::TSearcherConfig::sctBase);
    ApplyMainConfig(searchConfig.Get(), dir, NRTYServer::TSearcherConfig::sctMeta);

    if (Config.IsPrefixedIndex) {
        NUtil::TRearrangeOptionsHelper helper(*searchConfig->ProtoCollection_.MutableReArrangeOptions());
        helper.AddRule("KeyPrefixSupporter", "ShardsNumber=" + ToString(Config.Shards->Number));
    }
    if (Config.GetRealmListConfig().GetNumberDiskRealms() > 1) {
        NUtil::TRearrangeOptionsHelper helper(*searchConfig->ProtoCollection_.MutableReArrangeOptions());
        helper.AddRule("RTYServerAntiDup");
    }

    TIndexComponentsStorage::Instance().CorrectSearchConfig(*searchConfig.Get(), NRTYServer::TSearcherConfig::sctMeta);
    return searchConfig;
}

