/*
 * MIT License
 * Author: Mark Allyn
 *
 * traffic_cop.cpp — Thread 2 polling loop.
 */

#include "traffic_cop.h"
#include <chrono>
#include <array>

void TrafficCop::start() {
    running_ = true;
    thread_  = std::thread(&TrafficCop::run, this);
}

void TrafficCop::stop() {
    running_ = false;
    if (thread_.joinable())
        thread_.join();
}

void TrafficCop::run() {
    using namespace std::chrono;
    const auto interval = milliseconds(POLL_INTERVAL_MS);
    const float dt = POLL_INTERVAL_MS / 1000.0f;

    auto next = steady_clock::now() + interval;

    while (running_) {
        std::array<TargetState, MAX_TARGETS> buf{};
        int count = sim_.poll(dt, buf);
        tb_.write(buf, count);

        // Sleep until next poll time (drift-resistant)
        std::this_thread::sleep_until(next);
        next += interval;
    }
}
