/*
 * SPDX-FileCopyrightText: 2025 Copyright contributors to the cppTango project
 *
 * SPDX-License-Identifier: LGPL-3.0-or-later
 */
#ifndef TANGO_INTERNAL_EVENT_PERF_MONITOR_DOUBLEBUFFER_H
#define TANGO_INTERNAL_EVENT_PERF_MONITOR_DOUBLEBUFFER_H

#include <tango/internal/event_perf_monitor/RingBuffer.h>

#include <mutex>

namespace Tango
{
template <typename T>
struct DoubleBuffer
{
    void json_dump(std::ostream &os)
    {
        RingBuffer<T> *buffer = nullptr;
        {
            std::scoped_lock lg{lock};
            if(enabled)
            {
                std::swap(front, back);
                front->reset();
                buffer = back;
            }
        }

        if(buffer == nullptr)
        {
            os << "null";
        }
        else
        {
            buffer->json_dump(os);
        }
    }

    void enable(bool v)
    {
        std::scoped_lock lg{lock};
        enabled = v;
        if(v)
        {
            front->reset();
        }
    }

    std::mutex lock;
    RingBuffer<T> ring_buffers[2];
    RingBuffer<T> *front = &ring_buffers[0];
    RingBuffer<T> *back = &ring_buffers[1];
    bool enabled = false;
};
} // namespace Tango

#endif // TANGO_INTERNAL_EVENT_PERF_MONITOR_DOUBLEBUFFER_H
