#include "player_input.h"
#include "debug.h"

PlayerInput* playerinput_new(void* target, int device) {
    PlayerInput* self = malloc(sizeof(PlayerInput));
    ASSERT_RETURN(self != NULL, NULL, "Could not allocate memory for PlayerInput instance");
    self->listeners = list_from_type(InputListener);
    self->device = input_get_device_by_id(device);
    self->target = target;
    input_device_set_listeners(self->device, &self->listeners);
    return self;
}

void playerinput_add(PlayerInput* self, InputAxis axis, InputDelegateFn delegate) {
    InputListener listener = {
        .axis = axis,
        .fn = delegate,
        .self = self->target,
    };
    listener.axis.tc->set_device(listener.axis.data, self->device);
    list_add(&self->listeners, &listener);
}

void playerinput_set_device(PlayerInput* self, int device) {
    if(self->device != NULL)
        input_device_set_listeners(self->device, NULL);
    self->device = input_get_device_by_id(device);
    input_device_set_listeners(self->device, &self->listeners);
}

void playerinput_drop(PlayerInput* self) {
    input_device_set_listeners(self->device, NULL);

    list_foreach(InputListener*, listener, &self->listeners) {
        listener->axis.drop->drop(listener->axis.data);
    }
    list_empty(&self->listeners);
    free(self);
}
