#include "travel_time.h"

#include <maps/wikimap/mapspro/libs/masstransit/masstransit.h>
#include "thread_stops.h"

namespace maps::wiki::masstransit {

TravelTime::TravelTime(DBID travelTimeId, DBID threadId)
    : travelTimeId(travelTimeId)
    , threadId(threadId)
{ }

MtrTravelTimeHandler::MtrTravelTimeHandler(Masstransit& masstransit)
    : MtrObjectHandler(masstransit, masstransit.travelTimes)
{ }

void
MtrTravelTimeHandler::writeObject(StreamMap& ostreams, const Object& object)
{
    const auto& travelTime = dynamic_cast<const TravelTime&>(object);
    const auto mtrId = idMap().getMtrId(travelTime.travelTimeId);

    const auto& threadStops = masstransit_.threadStops[travelTime.threadId];
    if (!masstransit_.threads.count(threadStops.threadId)) {
        return;
    }
    REQUIRE(travelTime.data.size() == threadStops.stopsInThread.size(),
        "Different number of stops for thread_id = " +
        std::to_string(travelTime.threadId));

    size_t seqId = 0;
    for (size_t i = 0; i < travelTime.data.size(); ++i) {
        const auto& threadStop = threadStops.stopsInThread[i];
        const auto& travelTimeDatum = travelTime.data[i];

        REQUIRE(threadStop.seqId == travelTimeDatum.seqId,
            "Sequence id do not match: thread_id = " +
            std::to_string(travelTime.threadId) +
            ", thread_stop seq_id = " +
            std::to_string(threadStop.seqId) +
            ", travel_time seq_id = " +
            std::to_string(travelTimeDatum.seqId));

        const auto& stop = masstransit_.stops[threadStop.stopId];
        if (isWaypoint(threadStop.flags) || stop.isWaypoint) {
            continue;
        }

        auto& ostream = ostreams[fileNames().front()];
        ostream << mtrId << FIELD_SEPARATOR
                << seqId << FIELD_SEPARATOR
                << travelTimeDatum.arrivalTimeSec << FIELD_SEPARATOR
                << travelTimeDatum.departureTimeSec << std::endl;
        ++seqId;
    }
}

std::string getTravelTimeMtrId(DBID baseId)
{
    return std::to_string(baseId) + "_trip_0";
}

} // namespace maps::wiki::masstransit
