#include "game/npc.h"
#include "game/world.h"
#include "core/types.h"
#include "core/math.h"

void UpdateNPC(F32 delta, NPC *npc, World *world) {
  switch (npc->mode) {
    case NPC_ACTION_WAITING:
      npc->waitTime+=delta;
      if(npc->waitTime > npc->maxWaitTime) {
        npc->mode = NPC_ACTION_WALKING;
        // TODO change targets to poi's rather than just random nodes
        // TODO choose either global POI's or use NPC custom poi if
        // customPOI is true
        do {
          npc->targetNavNode = Random_U32(&world->random, 0, world->navMesh->nodeCount);
        } while(npc->targetNavNode == npc->currentNavNode);
        npc->path = Nav_Path(world->navMesh, npc->currentNavNode, npc->targetNavNode);
        npc->walkTimer = 0;
      }
    break;
    case NPC_ACTION_WALKING:
      npc->walkTimer+=delta;
      if(npc->walkTimer >= NPC_SPEED){
        npc->walkTimer = 0;
        if(npc->path.nodeCount == npc->pathIndex+1){
          npc->mode = NPC_ACTION_WAITING;
          npc->maxWaitTime = Random_F32(&world->random, 20, 140);
          npc->waitTime = 0;
          npc->currentNavNode = npc->targetNavNode;
          npc->pathIndex = 0;
          return;
        }
        npc->currentNavNode = npc->path.indexes[npc->pathIndex];
        npc->pathIndex+=1;
      }
      NavNode cNav = world->navMesh->nodes[npc->currentNavNode];
      NavNode tNav = world->navMesh->nodes[npc->path.indexes[npc->pathIndex]];
      npc->collision.pos.x = cNav.pos.x * (1 - npc->walkTimer/NPC_SPEED) + tNav.pos.x * npc->walkTimer/NPC_SPEED;
      npc->collision.pos.y = cNav.pos.y * (1 - npc->walkTimer/NPC_SPEED) + tNav.pos.y * npc->walkTimer/NPC_SPEED;
    break;
  }
}
