#include "../player.h"
#include <SDL3/SDL_events.h>
#include <SDL3/SDL_keycode.h>
#include <stdio.h>

void PlayerInput(SDL_Event *event, Player *player)
{
  player->controls.shot = false;
  SDL_KeyboardEvent key = event->key;
  SDL_MouseButtonEvent mouseBtn = event->button;
  if(event->type == SDL_EVENT_KEY_DOWN || event->type == SDL_EVENT_KEY_UP) {
    bool val = event->type == SDL_EVENT_KEY_DOWN;
    switch (key.key)
    {
      case SDLK_W:
      {
        player->controls.upDown = val;
        break;
      }
      case SDLK_A:
      {
        player->controls.leftDown = val;
        break;
      }
      case SDLK_D:
      {
        player->controls.rightDown = val;
        break;
      }
      case SDLK_S:
      {
        player->controls.downDown = val;
        break;
      }
    }
  }
  if (
    event->type == SDL_EVENT_MOUSE_BUTTON_DOWN 
    && mouseBtn.button == SDL_BUTTON_LEFT
  ) {
    if(player->bulletsLoaded > 0) {
      // shooting
      player->bulletsLoaded -= 1;
      player->controls.shot = true;
      player->shotPos = V2F(mouseBtn.x, mouseBtn.y);
      printf("shot %f %f\n", mouseBtn.x, mouseBtn.y);
    } else if(player->reloadTimer == 0) {
      player->reloadTimer = PLAYER_RELOAD_TIME;
      printf("reloading\n");
  };
  } 
}

void PlayerUpdate(F32 delta, Player *player) {
  V2f dir = V2F(0, 0);
  if(player->controls.upDown) {
    dir.y -= 1;
  }
  if(player->controls.downDown) {
    dir.y += 1;
  }
  if(player->controls.leftDown) {
    dir.x -= 1;
  }
  if(player->controls.rightDown) {
    dir.x += 1;
  }
  if(player->reloadTimer > 0) {
    player->reloadTimer-=delta;
    if(player->reloadTimer <= 0) {
      player->bulletsLoaded = PLAYER_BULLET_COUNT;
      player->reloadTimer = 0;
    }
  }
  dir = V2f_Scale(NormaliseV2F(dir), PLAYER_SPEED*delta);
  player->pos.x += dir.x;
  player->pos.y += dir.y;
}
