#include <robot/library/yt/static/command.h>
#include <robot/library/yt/static/table.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 <wmconsole/version3/processors/tools/IKS/utils/canonizer.h>
#include <wmconsole/version3/wmcutil/log.h>

#include "task_videohostings.h"

namespace NWebmaster {

using namespace NJupiter;

int TaskVideohostings(int, const char **) {
    const auto &cfg = NAchievements::TConfig::CInstance();
    NYT::IClientPtr client = NYT::CreateClient(cfg.MR_SERVER_HOST);
    NYT::ITransactionPtr tx = client->StartTransaction();

    LOG_INFO("achievements, videohostings, input %s", cfg.TABLE_SOURCE_VIDEOHOSTINGS_OFFERS.c_str());
    LOG_INFO("achievements, videohostings, input %s", cfg.TABLE_SOURCE_VIDEOHOSTINGS_GRADES.c_str());
    LOG_INFO("achievements, videohostings, output %s", cfg.TABLE_ACHIEVEMENTS_PREP_VIDEOHOSTINGS.c_str());

    TMap<TString, int> grades;

    auto readerOffers = TTable<NProto::TSrcVideohostingsOffers>(tx, cfg.TABLE_SOURCE_VIDEOHOSTINGS_OFFERS).GetReader();
    for (; readerOffers->IsValid(); readerOffers->Next()) {
        const auto &row = readerOffers->GetRow();
        if (row.GetStatus() == "REDUNDANT") {
            continue;
        }
        grades[TIKSCanonizer::GetOwner(row.GetHostUrl())] = 0;
    }

    auto readerGrades = TTable<NProto::TSrcVideohostingsGrades>(tx, cfg.TABLE_SOURCE_VIDEOHOSTINGS_GRADES).GetReader();
    for (; readerGrades->IsValid(); readerGrades->Next()) {
        const auto &row = readerGrades->GetRow();
        const TString owner = TIKSCanonizer::GetOwner(row.GetDomain());
        grades[owner] = Max<int>(grades[owner], row.GetGrade());
    }

    NProto::TPrepVideohostings dstMsg;
    auto writer = TTable<NProto::TPrepVideohostings>(tx, cfg.TABLE_ACHIEVEMENTS_PREP_VIDEOHOSTINGS).AsSortedOutput({"MascotOwner"}).GetWriter();
    for (const auto &obj : grades) {
        dstMsg.SetMascotOwner(obj.first);
        dstMsg.SetGrade(obj.second);
        writer->AddRow(dstMsg);
    }
    writer->Finish();

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

    return 0;
}

} //namespace NWebmaster
