#include "thread/Thread.h"

#include <threads.h>

#include "data/HashMap.h"

static Core::HashMap<Core::Thread::Id, thrd_t> threads;
static Core::Thread::Id idCounter = 0;

Core::Error Core::Thread::start(Id& id, Function f, void* p) {
    id = idCounter++;
    thrd_t* t = nullptr;
    CORE_RETURN_ERROR(threads.tryEmplace(t, id));
    if(thrd_create(t, f, p) != thrd_success) {
        (void)threads.remove(id);
        return Error::THREAD_ERROR;
    }
    return Error::NONE;
}

Core::Error Core::Thread::join(Id id, int* returnValue) {
    thrd_t* t = threads.search(id);
    if(t == nullptr) {
        return Error::INVALID_ID;
    }
    if(thrd_join(*t, returnValue) != thrd_success) {
        return Error::THREAD_ERROR;
    }
    return threads.remove(id);
}