#pragma once

#include <balancer/yt/log-tool/controller/common/convert.h>
#include <balancer/yt/log-tool/proto/schema.pb.h>

#include <mapreduce/yt/interface/client.h>

#include <util/generic/string.h>

namespace NBalancerYt {
    template<typename TLog>
    class TLastTimeNode: public NYT::IReducer<NYT::TTableReader<TLog>, NYT::TTableWriter<TLog>> {
    public:
        virtual void Do(
            NYT::TTableReader<TLog>* input,
            NYT::TTableWriter<TLog>* output) override
        {
            TMaybe<TLog> lastRow;
            for (; input->IsValid(); input->Next()) {
                if (input->GetRow().GetReqId()) {
                    if (!lastRow || input->GetRow().GetStartTime() > lastRow->GetStartTime()) {
                        lastRow = input->GetRow();
                    }
                } else {
                    output->AddRow(input->GetRow());
                }
            }
            if (lastRow) {
                output->AddRow(*lastRow);
            }
        }
    };
    REGISTER_REDUCER(TLastTimeNode<NBalancerYt::NProto::TLog>);
    REGISTER_REDUCER(TLastTimeNode<NBalancerYt::NProto::TResolvedLog>);
}
