#include <util/string/printf.h>

#include <wmconsole/version3/processors/tools/IKS/conf/config.h>

#include <wmconsole/version3/wmcutil/log.h>
#include <wmconsole/version3/wmcutil/tld.h>
#include <wmconsole/version3/wmcutil/yt/yt_utils.h>

#include "utils.h"

namespace NWebmaster {

NYT::TRichYPath DebugPath(const TString& path) {
    return NYT::TRichYPath(path);
    //return NYT::TRichYPath(path).AddRange(NYT::TReadRange().UpperLimit(NYT::TReadLimit().Key("http://afy.ru")));
}

ui64 GetIks(const THashMap<TString, ui64> &HostsIks, const TString &host, TAnsipamOwnerCanonizer &Owners) {
    ui64 iks = 0;
    TString sourceHostOwner, error;
    if (Owners.GetOwner(host, sourceHostOwner, error)) {
        if (HostsIks.contains(sourceHostOwner)) {
            iks = HostsIks.at(sourceHostOwner);
        }
    }
    return iks;
}

void GetTableListOnly(NYT::IClientBasePtr client, const TString &path, TDeque<TString> &tables) {
    TDeque<TString> tmp;
    NYT::TNode::TListType tableList = client->List(path);
    for (const NYT::TNode &node : tableList) {
        tmp.push_back(NYTUtils::JoinPath(path, node.AsString()));
    }
    tables.swap(tmp);
}

TString GetShardName(int shardNo) {
    return Sprintf("%04d", shardNo);
}

TString GetTld(const TString &domain) {
    TString tld;
    if (GetTld(domain, tld)) {
        return tld;
    }

    return "UNKNOWN_TLD";
}

void LoadIks(NYT::IClientBasePtr client, THashMap<TString, ui64> &hostsIks) {
    THashMap<TString, ui64> tmpIks;
    auto reader = client->CreateTableReader<NYT::TNode>(NIks::TConfig::CInstance().TABLE_IKS_DATA_ACCEPTED);
    for (; reader->IsValid(); reader->Next()) {
        const NYT::TNode &row = reader->GetRow();
        TString host = row["Host"].AsString();
        host.to_lower();
        ui64 iks = row["IKS"].AsUint64();
        if (iks > 0) {
            tmpIks[host] = iks;
        }
    }
    hostsIks.swap(tmpIks);
}

} // namespace NWebmaster
