#include <thread>
#include <unistd.h>
#include <mutex>
#include <list>
#include "manager.h"

namespace game{

namespace entityManager{

std::list<entity*> addList, entityList, deleteList;

std::mutex entityAddMutex;
std::thread *th;

volatile bool threadActive = true;
volatile uint32_t threadDelay = 30000;

void init()
{
    th = new std::thread([](){
         while(true)
         {
            entityAddMutex.lock();

            for(entity *en:deleteList)
            {
                entityList.remove(en);
                delete en;
            }

            for(entity *en:addList)
                entityList.push_back(en);

            deleteList.clear();
            addList.clear();

            entityAddMutex.unlock();

            if(!threadActive)
                break;

            if(!threadDelay)
            {
                usleep(100000);
                continue;
            }

            for(entity *en:entityList)
                en->update();

            usleep(threadDelay);
         }
    });
}

void add(entity *en)
{
    entityAddMutex.lock();
    addList.push_back(en);
    entityAddMutex.unlock();
}

void remove(entity *en)
{
    entityAddMutex.lock();
    deleteList.push_back(en);
    entityAddMutex.unlock();
}

void draw()
{
    entityAddMutex.lock();

    for(entity *en:entityList)
        en->draw();

    entityAddMutex.unlock();
}

void free()
{
    threadActive = false;
    th->join();
    delete th;

    for(entity *e:entityList)
        delete e;

    entityList.clear();
    addList.clear();
    deleteList.clear();
}

void setGameSpeed(uint32_t speed)
{
    threadDelay = speed;
}

uint32_t getGameSpeed()
{
    return threadDelay;
}

}

}
