#include "TestFramework.h"
#include "htio2/RingBuffer.h"

#include <vector>
#include <limits>

using namespace htio2::juce;
using namespace std;

#define NUM_DATA 10

htio2::RingBuffer<int> buffer(NUM_DATA * 2);

struct MyWorker: public Thread
{
    MyWorker(const String& name): Thread(name)
    {
        result.reserve(4096);
    }

    virtual void run() override
    {
        for (;;)
        {
            int value = numeric_limits<int>::max();

            if (buffer.pop(value))
            {
                printf("worker got %d\n", value);
                if (value == -1)
                    return;

                result.push_back(value);
            }

            yield();
        }
    }

    vector<int> result;
};


void TestFramework::content()
{
    MyWorker worker("worker");
    worker.startThread();

    for (int value = 0; value < NUM_DATA; value++)
    {
        while (!buffer.push(value)) {Thread::yield();}
        printf("pushed %d\n", value);
    }

    while (!buffer.push(-1)) {Thread::yield();}

    worker.waitForThreadToExit(-1);

    for (int value = 0; value < NUM_DATA; value++)
    {
        if (worker.result[value] != value)
        {
            fprintf(stderr, "expect %d, got %d\n", value, worker.result[value]);
            exit(EXIT_FAILURE);
        }
    }
}
