#include <util/draft/date.h>
#include <util/generic/set.h>
#include <util/thread/pool.h>
#include <util/generic/singleton.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 <kernel/urlnorm/normalize.h>
#include <ctime>

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

namespace NWebmaster {

using namespace NJupiter;

struct TMetrikaMapper : public NYT::IMapper<NYT::TTableReader<NProto::TSrcMetrika>, NYT::TTableWriter<NProto::TPrepMetrika>> {
    void Do(TReader *input, TWriter *output) override {
        NProto::TPrepMetrika metrika;
        for (; input->IsValid(); input->Next()) {
            TString owner = GetOwner(input->GetRow().GetHost());
            TString normalized;
            if (NUrlNorm::NormalizeUrl(owner, normalized)){
                metrika.SetMascotOwner(owner);
                output->AddRow(metrika);
            }
        }
    }
};

REGISTER_MAPPER(TMetrikaMapper)

struct TMetrikaReducer : public NYT::IReducer<NYT::TTableReader<NProto::TPrepMetrika>, NYT::TTableWriter<NProto::TPrepMetrika>> {
    void Do(TReader *input, TWriter *output) override {
        if (input->IsValid()) {
            NProto::TPrepMetrika metrika;
            metrika.SetMascotOwner(input->GetRow().GetMascotOwner());
            output->AddRow(metrika);
        }
    }
};

REGISTER_REDUCER(TMetrikaReducer)

int AboutMetrikaHosts(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);

    TDeque <NYTUtils::TTableInfo> tables;
    TDeque <TString> deque;
    NYTUtils::GetTableList(client, TConfig::CInstance().TABLE_SOURCE_METRIKA, tables);

    for (const auto &table: tables) {
        deque.push_back(NWebmaster::NYTUtils::GetTableName(table.Name));
    }

    TString tableTimestamp;
    TString maxSourceTimestamp = "-1";
    try {
        maxSourceTimestamp = deque.front();
        tableTimestamp = GetYtAttr(client, cfg.TABLE_SERVICES_PREP_METRIKA, cfg.ATTR_UPDATE_SOURCE).AsString();
    } catch (yexception &) {
    }

    if (tableTimestamp == maxSourceTimestamp){
        LOG_INFO("achievements, metrika, Db already updated!");
        return 0;
    }


    NYT::ITransactionPtr tx = client->StartTransaction();

    auto iterator = deque.begin();
    auto mapReduce = TMapReduceCmd<TMetrikaMapper, TMetrikaReducer>(tx);

    for (int i = 0; i < 28 && iterator != deque.end(); i++,iterator++) {
        mapReduce.Input(TTable<NProto::TSrcMetrika>(tx, NYTUtils::JoinPath(cfg.TABLE_SOURCE_METRIKA, *iterator)));
    }

    LOG_INFO("achievements, metrika, Reduce start");

    mapReduce.Output(TTable<NProto::TPrepMetrika>(tx, cfg.TABLE_SERVICES_PREP_METRIKA))
            .OperationWeight(cfg.OPERATION_WEIGHT)
            .ReduceBy({"MascotOwner"})
            .Do();

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

    LOG_INFO("achievements, metrika, Reduce done");
    LOG_INFO("achievements, metrika, Sort start");

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


    tx->Commit();

    LOG_INFO("achievements, metrika, Done");

    return 0;
}
} //namespace NWebmaster
