#include "split_into_tracks.h"

#include "signal.h"
#include "track.h"

#include <maps/libs/geolib/include/distance.h>

namespace maps {
namespace wiki {
namespace signals_graph {
namespace {

const int MAX_SIGNALS_TIME_DIFFERENCE = 45; // seconds
const double MAX_SIGNALS_DISTANCE = 500.0; // meters

bool isCuttingPlace(const Signal& previous, const Signal& current) {
    bool res;

    if (current.uuid != previous.uuid) {
        res = true;
    } else if (current.timestamp - previous.timestamp > MAX_SIGNALS_TIME_DIFFERENCE) {
        res = true;
    } else {
        double distance = geolib3::geoDistance(
            current.geoPoint,
            previous.geoPoint
        );

        if (distance > MAX_SIGNALS_DISTANCE) {
            res = true;
        } else {
            res = false;
        }
    }

    return res;
}

} // namespace

std::vector<Track> splitIntoTracks(const std::vector<Signal>& signals) {
    std::vector<Track> result;

    if (signals.empty()) {
        return result;
    }

    auto signalsIt = signals.begin();
    auto trackBegin = signalsIt;

    Signal previous = *signalsIt++;

    for (; signalsIt != signals.end(); ++signalsIt) {
        if (isCuttingPlace(previous, *signalsIt)) {
            result.push_back(Track({trackBegin, signalsIt}));
            trackBegin = signalsIt;
        }

        previous = *signalsIt;
    }

    return result;
}

} // namespace maps
} // namespace wiki
} // namespace signals_graph
