#include "lost_reducer.h"
#include "common.h"
#include "column_names.h"

#include <unordered_map>

namespace mjs = maps::jams::static_graph2;

namespace maps::wiki::route_lost_feedback {

// This reducer makes two actions:
// 1) count overall number of route-losts, identified by reduce KEY
// 2) from all route-losts with this KEY find one with maximal
//    traffic at 'after-after-lost-track-segment'
//
void LostReducer::Do(TReader* reader, TWriter* writer)
{
    std::unordered_map<mjs::PersistentSegmentId, uint64_t> frequency;

    auto resRow = reader->GetRow();
    reader->Next();

    ++frequency[
        asPersistentSegment(
            resRow[column_names::AFTER_AFTER_LOST_TRACK_SEGMENT]
        )
    ];

    uint64_t countRows = 1;
    uint64_t maxCount = 1;

    for (; reader->IsValid(); reader->Next()) {
        const auto& curRow = reader->GetRow();

        uint64_t curCount =
            ++frequency[
                asPersistentSegment(
                    curRow[column_names::AFTER_AFTER_LOST_TRACK_SEGMENT]
                )
            ];

        if (curCount > maxCount) {
            maxCount = curCount;
            resRow = curRow;
        }

        countRows++;
    }

    writer->AddRow(NYT::TNode(resRow)(column_names::LOSTS_NUMBER, countRows));
}

REGISTER_REDUCER(LostReducer);

} // namespace maps::wiki::route_lost_feedback
