#include <util/draft/date.h>
#include <util/generic/queue.h>

#include <library/cpp/getopt/last_getopt.h>

#include <robot/library/yt/static/command.h>
#include <robot/library/yt/static/table.h>

#include <wmconsole/version3/library/jupiter/jupiter.h>
#include <wmconsole/version3/wmcutil/log.h>
#include <wmconsole/version3/processors/achievements/conf/config.h>
#include <wmconsole/version3/processors/achievements/protos/sources.pb.h>
#include <wmconsole/version3/processors/achievements/protos/achievements.pb.h>

#include <library/cpp/json/json_reader.h>
#include <library/cpp/json/json_writer.h>

#include <limits.h>

#include "import_util.h"
#include "task_about_iks.h"

namespace NWebmaster {

using namespace NJupiter;

struct TCounterMapper : public NYT::IMapper<NYT::TTableReader<NProto::TSrcIks>, NYT::TTableWriter<NProto::TPrepIks>> {
    void Do(TReader *input, TWriter *output) override {

        NProto::TPrepIks iks;
        for (; input->IsValid(); input->Next()) {
            const auto &row = input->GetRow();
            iks.SetMascotOwner(row.GetHost());
            iks.SetIks(row.GetIks());
            output->AddRow(iks);
        }
    }
};

REGISTER_MAPPER(TCounterMapper)

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

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

    time_t tableTimestamp;
    try {
        tableTimestamp = GetYtAttr(client, cfg.TABLE_ACHIEVEMENTS_PREP_IKS, cfg.ATTR_UPDATE_TIME).AsInt64();
    } catch (yexception &) {
        tableTimestamp = std::numeric_limits<time_t>::min();
    }

    time_t maxSourceTimestamp;
    try {
        maxSourceTimestamp = GetYtAttr(client, cfg.TABLE_SOURCE_IKS, cfg.ATTR_UPDATE_TIME).AsInt64();
    } catch (yexception &) {
        maxSourceTimestamp = std::numeric_limits<time_t>::max();
    }

    if (maxSourceTimestamp <= tableTimestamp){
        LOG_INFO("achievements, IKS, Iks db already updated!");
        return 0;
    }

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

    NYT::ITransactionPtr tx = client->StartTransaction();
    TMapCmd<TCounterMapper>(tx)
            .Input(TTable<NProto::TSrcIks>(tx, cfg.TABLE_SOURCE_IKS))
            .Output(TTable<NProto::TPrepIks>(tx, cfg.TABLE_ACHIEVEMENTS_PREP_IKS))
            .Do();

    LOG_INFO("achievements, IKS, Map done");

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

    SetYtAttr(tx, cfg.TABLE_ACHIEVEMENTS_PREP_IKS, cfg.ATTR_UPDATE_TIME, maxSourceTimestamp);

    tx->Commit();
    LOG_INFO("achievements, IKS, iks task done");

    return 0;
}

} //namespace NWebmaster
