#include "event.h"
#include "basic.h"

#ifdef __cplusplus
extern "C" {
#endif

static int enabled = 0;
static voidFunc callbacks[MAX_EVENT_NU];
static int8_t eventMap[MAX_EVENT_NU];
static int8_t NUM;

void tick(MicroBitEvent e)
{
  for(int map = 0 ; map < MAX_EVENT_NU; map++)
  {
    if(eventMap[map] == e.source)  callbacks[map]();
  }
}

static void __initiali_()
{
  NUM = 0;
  memset(callbacks, 0, sizeof(callbacks));
  memset(eventMap, -1, sizeof(eventMap));
}

void onEvent(ID id, EVENT event, voidFunc callback)
{
  if (!enabled) {
    __initiali_();
    enabled = 1;
  }
  
  for(int ch = 0; ch < MAX_EVENT_NU; ch++){
    if (eventMap[ch] == -1 || (uint32_t)eventMap[ch] == id) {
      eventMap[ch] = id;
      callbacks[ch] = callback;
      NUM++;
      if(id == ID_BUTTON_A || id == ID_BUTTON_B || id == ID_BUTTON_AB)
        uBit.messageBus.listen((int)id, event, tick);
      else {
        MicroBitPin *pin = getMicroBitPin(id);
        if (!pin) return;
        // Forces the PIN to switch to makey-makey style detection.
        pin->isTouched();
        uBit.messageBus.listen((int)id, event, tick);
      }
      break;
    }
  }
}

#ifdef __cplusplus
}
#endif