/**
 * Copyright (c) 2021 Dominic Masters
 * 
 * This software is released under the MIT License.
 * https://opensource.org/licenses/MIT
 */

#include "action.h"

void pokerActionInit() {
  // Free up all actions
  memset(GAME_STATE.actionQueue, (int32_t)NULL,
    sizeof(pokeraction_t) * POKER_ACTION_QUEUE_SIZE
  );

  // Free up all data
  memset(GAME_STATE.actionData, (int32_t)NULL, sizeof(void *) *
    POKER_ACTION_DATA_SIZE * POKER_ACTION_QUEUE_SIZE
  );
}

int32_t pokerActionAdd(pokeraction_t action) {
  int32_t i = -1;
  int32_t j = -1;

  for(i = 0; i < POKER_ACTION_QUEUE_SIZE; i++) {
    if(GAME_STATE.actionQueue[i].init != NULL) continue;
    j = i;
    break;
  }
  if(j == -1) return j;

  GAME_STATE.actionQueue[j] = action;
  GAME_STATE.actionInitState[j] = false;
  return j;
}

void pokerActionRemove(int32_t index) {
  if(GAME_STATE.actionQueue[index].dispose != NULL) {
    GAME_STATE.actionQueue[index].dispose(
      index, GAME_STATE.actionData + index
    );
  }

  memset(GAME_STATE.actionQueue+index, (int32_t)NULL,
    sizeof(pokeraction_t)
  );

  memset(GAME_STATE.actionData+index, (int32_t)NULL,
    sizeof(void *) * POKER_ACTION_DATA_SIZE
  );
}

void pokerActionUpdate() {
  int32_t i;
  void **data;
  pokeraction_t *action;

  for(i = 0; i < POKER_ACTION_QUEUE_SIZE; i++) {
    action = GAME_STATE.actionQueue + i;
    data = GAME_STATE.actionData + i;

    if(action->init != NULL && !GAME_STATE.actionInitState[i]) {
      GAME_STATE.actionInitState[i] = true;
      action->init(i, data);
    }

    if(action->update != NULL) {
      action->update(i, data);
    }
  }
}

void pokerActionDispose() {
  int32_t i;
  for(i = 0; i < POKER_ACTION_QUEUE_SIZE; i++) {
    if(GAME_STATE.actionQueue[i].dispose == NULL) continue;
    GAME_STATE.actionQueue[i].dispose(i, GAME_STATE.actionData+i);
  }
}