#include "../world.h"
#include "../npc.h"
#include "../player.h"
#include <SDL3/SDL_events.h>

void UpdateWorld(F32 delta, World *world)
{
  UpdateBandit(delta, &world->bandit, world);
  UpdateNPCs(delta, world);
  PlayerUpdate(delta, &world->player);
}

void UpdateNPCs(F32 delta, World *world)
{
  for (U32 i = 0; i < world->npcCount; i++)
  {
    UpdateNPC(delta, &world->npcs[i], world);
    if(world->player.controls.shot && AABB_Point(world->npcs[i].collision, world->player.shotPos)) {
      // TODO we need to unproject the mouse location !!!
      printf("You shot %.*s\n", Sv(world->npcs[i].name));
    }
  }
}

void ProcessEvents(SDL_Event *event, World *world)
{
  PlayerInput(event, &world->player);
}

void RenderWorld(World *world, D_Context *draw) {
  for(U32 i = 0; i < world->npcCount; i++) {
    NPC npc = world->npcs[i];
    D_Rect(draw, npc.collision.pos.x, npc.collision.pos.y, .texture = 1);
    D_Rect(draw, npc.collision.pos.x, npc.collision.pos.y, .texture = 0, .dim = npc.collision.size);
  }
  D_Rect(draw, world->bandit.collision.pos.x, world->bandit.collision.pos.y, .texture = 9);
  D_Rect(draw, world->player.pos.x, world->player.pos.y, .texture = 1);
}

void G_WorldDraw(G_State *game, World *world) {
	D_Context *draw = &game->draw;

	(void) world;

	U32 id     = D_ImageHandle(&game->draw, S("tile_dirt_0"));
	U32 alt_id = D_ImageHandle(&game->draw, S("tile_dirt_1"));

	for (F32 y = -128; y < 128; y += 1.0f) {
		for (F32 x = -128; x < 128; x += 1.0f) {
			U32 ux = (U32) x;
			U32 uy = (U32) y;

			U32 tid = id;
			if ((ux % 11) == 0 || ((uy % 7) == 0)) {
				tid = alt_id;
			}

			D_Rect(draw, x, y, .texture = tid);
		}
	}
}
