#include <util/draft/date.h>
#include <util/generic/set.h>
#include <util/thread/pool.h>

#include <robot/library/yt/static/command.h>
#include <robot/library/yt/static/table.h>
#include <yql/library/embedded/yql_embedded.h>
#include <kernel/urlnorm/normalize.h>

#undef LOG_DEBUG
#undef LOG_INFO
#undef LOG_ERROR

#include <wmconsole/version3/processors/siteservices/protos/sources.pb.h>
#include <wmconsole/version3/processors/siteservices/protos/services.pb.h>
#include <wmconsole/version3/processors/siteservices/conf/config.h>
#include <wmconsole/version3/wmcutil/yt/transfer_manager.h>

#include <ctime>

#include "task_about_direct_hosts.h"
#include "import_util.h"

namespace NWebmaster {
using namespace NJupiter;

int AboutDirectHosts(int, const char **) {
    const auto &cfg = TConfig::CInstance();
    NYT::IClientPtr client = NYT::CreateClient(cfg.MR_SERVER_HOST);

    NYTUtils::CreatePath(client, cfg.TABLE_SERVICES_PREP_ROOT);

    TString tableTimestamp;
    TString maxSourceTimestamp = "-1";
    try {
        tableTimestamp = GetYtAttr(client, cfg.TABLE_SERVICES_PREP_DIRECT, cfg.ATTR_UPDATE_SOURCE).AsString();
        maxSourceTimestamp = GetYtAttr(client, cfg.TABLE_SOURCE_DIRECT, cfg.ATTR_UPLOAD_TIME).AsString();
    } catch (yexception &) {
    }

    if (tableTimestamp.equal(maxSourceTimestamp)){
        LOG_INFO("achievements, DirectHosts, Db already updated!");
        return 0;
    }

    LOG_INFO("achievements, DirectHosts, Start import table");
    NYT::ITransactionPtr tx = client->StartTransaction();
    auto reader = tx->CreateTableReader<NProto::TSrcDirect>(cfg.TABLE_SOURCE_DIRECT);
    auto writer = tx->CreateTableWriter<NProto::TPrepDirect>(cfg.TABLE_SERVICES_PREP_DIRECT);
    NProto::TPrepDirect prepDirect;

    for (; reader->IsValid(); reader->Next()) {
        const auto &row = reader->GetRow();
        TString normalized;
        if (NUrlNorm::NormalizeUrl(row.GetUniqDomain(), normalized)){
            prepDirect.SetMascotOwner(GetOwner(normalized));
            writer->AddRow(prepDirect);
        }
    }

    writer->Finish();

    SetYtAttr(tx, cfg.TABLE_SERVICES_PREP_DIRECT, cfg.ATTR_UPDATE_SOURCE, maxSourceTimestamp);

    TSortCmd<NProto::TPrepDirect>
            (tx, TTable<NProto::TPrepDirect>(tx, cfg.TABLE_SERVICES_PREP_DIRECT))
            .By({"MascotOwner"})
            .OperationWeight(cfg.OPERATION_WEIGHT)
            .Do();

    tx->Commit();

    LOG_INFO("achievements, DirectHosts, Import done");
    return 0;
}
} //namespace NWebmaster
