#include "local.h"

DEFINE_COMPONENT(Event)

static uint32_t _events_id = 1;

uint32_t Engine_next_event_id(void) {
  return _events_id++;
}

QUERY( _update_events
  , state(uint32_t, last_highest_seen)
  , state(struct CmdBuf, cbuf)
  , state(uint32_t, next_highest_seen)
  , pre(
    CmdBuf_begin_recording(&state->cbuf);
    state->next_highest_seen = state->last_highest_seen;
  )
  , read(Event, e)
  , action(
    if(e->id <= state->last_highest_seen) {
      CmdBuf_despawn(&state->cbuf, entity);
    } else if(e->id > state->next_highest_seen) {
      state->next_highest_seen = e->id;
    }
  )
  , post(
    state->last_highest_seen = state->next_highest_seen;
    CmdBuf_end_recording(&state->cbuf);
    CmdBuf_execute(&state->cbuf, Engine_ecs());
  )
)