//
// Created by sebastian on 08.02.26.
//

#include "BuildingPlacementSystem.h"

#include "../../RessourceType.h"
#include "../../../../engine/core/Application.h"
#include "../../../../engine/core/ECS/ModelComponent.h"
#include "../../../../engine/core/ECS/TileRenderComponent.h"
#include "../../../../engine/core/ECS/TransformComponent.h"
#include "../../../../engine/platform/glfw/InputManager.h"
#include "../../../../engine/renderer/model/AssetManager.h"
#include "../components/BuildingComponent.h"
#include "../components/TileGameplayComponent.h"
#include "GLFW/glfw3.h"

void BuildingPlacementSystem::update(EntityManager& entityManager, GameMode& gameMode, PlayerID player) {
    if (!InputManager::isMouseButtonPressed(GLFW_MOUSE_BUTTON_LEFT)) {
        return;
    }

    for (EntityID entityID : entityManager.getAllEntities()) {
        auto transformComponent = entityManager.getComponent<TransformComponent>(entityID);
        auto tileGameplayComponent = entityManager.getComponent<TileGameplayComponent>(entityID);
        auto tileRenderComponent = entityManager.getComponent<TileRenderComponent>(entityID);

        if (!transformComponent || !tileGameplayComponent || !tileRenderComponent) continue;

        // Tile is not in focus or tile has already a building
        if (!tileRenderComponent->isHighlighted || tileGameplayComponent->hasBuilding()) continue;

        if (!gameMode.canBuild(player, BuildingType::FOREST_HUT)) continue;

        gameMode.build(player, entityID, BuildingType::FOREST_HUT);
        for (auto oldID : tileGameplayComponent->entitiesOnTile) {
            entityManager.destroyEntity(oldID);
        }
        tileGameplayComponent->entitiesOnTile.clear();

        EntityID buildingEntity = entityManager.createEntity();
        entityManager.addComponent(buildingEntity, std::make_shared<ModelComponent>(AssetManager::getModel("cabin")));
        entityManager.addComponent(buildingEntity, std::make_shared<TransformComponent>(transformComponent->position, glm::vec3(0), 1.f));
        entityManager.addComponent(buildingEntity, std::make_shared<BuildingComponent>(BuildingType::FOREST_HUT, entityID));
        entityManager.addComponent(buildingEntity, std::make_shared<OwnerComponent>(player));
        tileGameplayComponent->buildingEntityID = buildingEntity;
    }
}
