#ifndef MEMQUEUE_H
#define MEMQUEUE_H

#include <string>
#include <mutex>

class MemQueueItem
{
public:
    MemQueueItem *next;
    std::string _event;
    int         _wv;
};

class MemQueue
{
private:
    std::mutex    _mutex;
    int           _depth;
    MemQueueItem *_first;
    MemQueueItem *_last;

public:
    void enqueue(int w, std::string s) {
        _mutex.lock();
        MemQueueItem *item = new MemQueueItem();
        item->next = nullptr;
        item->_event = s;
        item->_wv = w;
        if (_last == nullptr) {
            _last = item;
            _first = item;
        } else {
            _last->next = item;
            _last = item;
        }
        _depth += 1;
        _mutex.unlock();
    }

    bool dequeue(int &wv, std::string &s) {
        _mutex.lock();
        if (_first == nullptr) {
            _mutex.unlock();
            return false;
        }
        MemQueueItem *item = _first;
        _first = _first->next;
        if (_first == nullptr) {
            _last = nullptr;
        }
        s = item->_event;
        wv = item->_wv;
        free(item);
        _depth -= 1;
        _mutex.unlock();
        return true;
    }

    int depth() {
        return _depth;
    }

public:
    MemQueue() {
        _depth = 0;
        _first = nullptr;
        _last = nullptr;
    }
};

#endif // MEMQUEUE_H
