#include "systems.h"

#include "../game_state.h"
#include "../ai_actions.h"


void updateAISystem(ecs_iter_t *it) {
    Game       *game  = ecs_singleton_get_mut(ECS, Game);
    BzBTState  *state = ecs_field(it, BzBTState, 1);

    f32 dt = GetFrameTime();

    for (i32 i = 0; i < it->count; i++) {
        ecs_entity_t entity = it->entities[i];
        if (state[i].root == NULL) {
            // No behaviour
            continue;
        }
        if (ecs_has(ECS, entity, AIBlackboard)) {
            AIBlackboard *blackboard = ecs_get_mut(ECS, entity, AIBlackboard);
            blackboard->entity = entity;
            state[i].userData = blackboard;
        }
        bzBTExecute(&state[i], dt);
    }
}

void setAIBehaviour(ecs_entity_t entity, const BzBTNode *root,
                    const AIBlackboard *blackboard) {
    Game *game = ecs_singleton_get_mut(ECS, Game);
    BZ_ASSERT(ecs_has(ECS, entity, BzBTState));
    BZ_ASSERT(!blackboard || ecs_has(ECS, entity, AIBlackboard));

    if (blackboard) {
        AIBlackboard *b = ecs_get_mut(ECS, entity, AIBlackboard);
        *b = *blackboard;
        if (b->proximity < 2.0f)
            b->proximity = 2.0f;
    }

    BzBTState *state = ecs_get_mut(ECS, entity, BzBTState);
    bzBTDestroyState(state);
    *state = bzBTCreateState(&(BzBTStateDesc) {
        .root = root,
        .pool = game->pools.btNodeState
    });
}
