#include "entity_factory.h"

#include "ai_actions.h"

ecs_entity_t entityCreateEmpty() {
    ecs_entity_t e = ecs_new_id(ECS);
    ecs_add_id(ECS, e, GameEntity);
    return e;
}

ecs_entity_t entityCreateWorker(const Position position, Game *game) {
    const Size size = {10.0f, 10.0f};
    BzTileset *tileset = &game->tileset;
    ecs_entity_t e = entityCreateEmpty();
    ecs_set_ptr(ECS, e, Position, &position);
    ecs_set_ptr(ECS, e, Size, &size);
    BzSpatialGridID spatialID = bzSpatialGridInsert(game->entityGrid, &e,
                                                    position.x - size.x * 0.5f, position.y - size.y * 0.5f,
                                                    size.x, size.y);
    ecs_set(ECS, e, SpatialGridID, { spatialID });
    ecs_set(ECS, e, Rotation, { 0.0f });
    ecs_set(ECS, e, Orientation, {0.0f});
    ecs_set(ECS, e, Velocity, {});
    ecs_set(ECS, e, Steering, {});
    TextureRegion workerRegion = {
            tileset->tiles,
            bzTilesetGetTileRegion(tileset, ENTITY_WORKER)
    };
    ecs_set_ptr(ECS, e, TextureRegion, &workerRegion);
    ecs_set(ECS, e, Animation, {
        .entityType = ENTITY_WORKER,
        .animType = ANIM_IDLE,

        .sequence = entityGetAnimationSequence(ENTITY_WORKER, ANIM_IDLE),
        .tileset = tileset,
        .curFrame = 0,
        .elapsed = 0.0f,
    });
    ecs_set(ECS, e, BzBTState, {
        .root = NULL,
        .nodeStatePool = game->pools.btNodeState
    });
    ecs_set(ECS, e, AIBlackboard, {.entity = e});
    ecs_add_id(ECS, e, Selectable);
    ecs_set(ECS, e, Unit, {
        .acceleration = 80.0f,
        .maxSpeed = 15.0f,
        .deceleration = 0.1f
    });
    ecs_set(ECS, e, Worker, {
        .collectSpeed = 0.8f,
        .depositSpeed = 0.2f,
        .carryCapacity = 5,
    });

    ecs_entity_t right = entityCreateEmpty();
    Arms arms = {.primary = right};
    ecs_set_ptr(ECS, e, Arms, &arms);
    ecs_set(ECS, right, Arm, {.offset = 45.0f, 4.5f});

    ecs_set(ECS, right, Size, {8, 8});
    ecs_set(ECS, right, Rotation, { 0.0f });
    TextureRegion daggerRegion = {
            tileset->tiles,
            bzTilesetGetTileRegion(tileset, getItemTile(ITEM_AXE))
    };
    ecs_set_ptr(ECS, right, TextureRegion, &daggerRegion);

    return e;
}
