#include <stdlib.h>

#include "../include/effect.h"
#include "../include/util.h"
#include "../include/const.h"

effect_t *effect_create(pos_t pos, effect_e type) {
  effect_t *effect = malloc(sizeof(effect_t));
  effect->type = type;
  effect->pos = pos;
  switch (type) {
    case EFFECT_FALL:
      effect->timer = fz_timer_create(7, 3);
      break;
    case EFFECT_BREAK:
      effect->timer = fz_timer_create(10, 3);
      break;
    case EFFECT_PARTICLE:
      effect->timer = fz_timer_create(14, 4);
      break;
  }
  effect->count = 0;
  return effect;
}

void effect_update(effect_t *effect, game_t *game) {
  fz_timer_update(effect->timer);
  if (fz_timer_check(effect->timer)) {
    effect->count++;
  }
  // remove effect after one iteration
  if (effect->count > 0) {
    for (int i = 0; i < game->effects_len; i++) {
      if (game->effects[i] == effect) {
        if (i + 1 < game->effects_len) {
          for (int j = i; j < game->effects_len - 1; j++) {
            game->effects[j] = game->effects[j + 1];
          }
        }
        game->effects_len--;
        game->effects = realloc(game->effects, sizeof(effect_t) * game->effects_len);
        break;
      }
    }
  }
}

void effect_draw(effect_t *effect, game_t *game) {
  int x;
  switch (effect->type) {
    case EFFECT_FALL:
      x = 1;
      break;
    case EFFECT_BREAK:
      x = 0;
      break;
    case EFFECT_PARTICLE:
      x = 3;
      break;
  }
  int frame = fz_timer_get(effect->timer);
  DrawTextureRec(game->assets.entities, texture_rect(frame, x, PLAYER_WIDTH, PLAYER_HEIGHT), pos_snap(effect->pos), WHITE);
}

void effect_free(effect_t *effect) {
  free(effect);
}

void effect_play(pos_t pos, effect_e type, game_t *game) {
  game->effects = realloc(game->effects, sizeof(effect_t) * (game->effects_len + 1));
  game->effects[game->effects_len] = effect_create(pos, type);
  game->effects_len++;
}
