/*
 * MIT License
 * Author: Mark Allyn
 *
 * target_buffer.h — thread-safe buffer that holds the most-recent set
 * of target states produced by the Simulator (Thread 4) and consumed
 * by Thread 1 (display) after being written through TrafficCop (Thread 2).
 *
 * Protected by Mutex B.  Only Thread 2 writes; Thread 1 reads via
 * a snapshot copy taken under the lock.
 */

#pragma once
#include <array>
#include <mutex>
#include <cstdint>
#include "settings.h"

// One target's position as seen by a scope's rendering code.
// All values are in the scope's native polar coordinate space.
struct TargetState {
    uint64_t id           = 0;
    float    range_m      = 0.0f;   // metres from radar origin
    float    bearing_deg  = 0.0f;   // degrees true, CW from north
    float    brightness   = 0.0f;   // 0-1, from radar equation
    float    size_m       = 50.0f;  // physical blob half-radius in metres; scope normalises to [0,1]
    bool     valid        = false;
};

class TargetBuffer {
public:
    // Thread 2 writes a new snapshot under the lock.
    void write(const std::array<TargetState, MAX_TARGETS>& src, int count);

    // Thread 1 copies the current snapshot under the lock.
    // Returns the number of valid targets copied.
    int  read(std::array<TargetState, MAX_TARGETS>& dst) const;

    // Generation counter — Thread 1 can check whether data changed.
    uint64_t generation() const;

private:
    mutable std::mutex mutex_;
    std::array<TargetState, MAX_TARGETS> data_{};
    int      count_     = 0;
    uint64_t gen_       = 0;
};
