#include "glass_evloop.h"

#include <glib.h>
#include <malloc.h>

static GSList * evloopHookList;

#define GEVL_HOOK_REGISTRATION_IMPL(ptr) ((GevlHookRegistrationImpl *) ptr)

typedef struct _GevlHookRegistrationImpl {
    GevlHookFunction hookFn;
    void * data;
} GevlHookRegistrationImpl;

void
glass_evloop_initialize() {
}

void
glass_evloop_finalize() {
    GSList * ptr = evloopHookList;
    while (ptr != NULL) {
        free(ptr->data);
        ptr = g_slist_next(ptr);
    }

    g_slist_free(evloopHookList);
    evloopHookList = NULL;
}

void
glass_evloop_call_hooks(GdkEvent * event) {
    GSList * ptr = evloopHookList;
    while (ptr != NULL) {
        GevlHookRegistrationImpl * hookReg =
                GEVL_HOOK_REGISTRATION_IMPL(ptr->data);
        hookReg->hookFn(event, hookReg->data);
        
        ptr = g_slist_next(ptr);
    }
}

GevlHookRegistration
glass_evloop_hook_add(GevlHookFunction hookFn, void * data) {
    GevlHookRegistrationImpl * hookReg =
            (GevlHookRegistrationImpl *)
                malloc(sizeof(GevlHookRegistrationImpl));
    
    if (hookReg != NULL) {
        hookReg->hookFn = hookFn;
        hookReg->data = data;

        evloopHookList = g_slist_prepend(evloopHookList, hookReg);
    }

    return hookReg;
}

void
glass_evloop_hook_remove(GevlHookRegistration hookReg) {
    evloopHookList = g_slist_remove(evloopHookList, hookReg);
    free(hookReg);
}

