#pragma once
// ── CS2 External C++ WebRadar — Threaded Service Base ────────────────────────
// Matches C# ThreadedServiceBase: creates a thread that runs FrameAction() in a
// loop with a configurable sleep interval.

#include <thread>
#include <chrono>
#include <atomic>
#include <memory>

class ThreadedServiceBase {
public:
    ThreadedServiceBase() = default;
    virtual ~ThreadedServiceBase() { dispose(); }

    // Start the background thread. If already running, this is a no-op.
    void start() {
        if (m_running.load()) return;
        m_running = true;
        m_thread = std::thread(&ThreadedServiceBase::thread_loop, this);
    }

    // Signal stop and join the thread.
    void dispose() {
        if (!m_running.load()) return;
        m_running = false;
        if (m_thread.joinable())
            m_thread.join();
    }

    bool is_running() const { return m_running.load(); }

protected:
    // Override this: called in a loop from the background thread.
    virtual void frame_action() = 0;

    // Sleep interval between frames. Default 20ms (50 updates/sec).
    std::chrono::milliseconds thread_frame_sleep{20};

private:
    void thread_loop() {
        while (m_running.load()) {
            frame_action();
            std::this_thread::sleep_for(thread_frame_sleep);
        }
    }

    std::thread m_thread;
    std::atomic<bool> m_running{false};
};
