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

#include "ForestTileGenerator.h"

#include "../../../engine/renderer/model/AssetManager.h"
#include "glm/detail/func_geometric.inl"


std::vector<std::shared_ptr<Entity>> ForestTileGenerator::generateHexTile(Random& random, glm::vec3 tilePos, std::vector<std::shared_ptr<Entity>> &mapEntities) const {
    int treeCount = random.randomInt(minTreeCount, maxTreeCount);

    std::vector<std::shared_ptr<Entity>> entitiesOnTile;
    std::shared_ptr<TexturedModel> treeModel = AssetManager::getModel("lowPolyTree");
    std::shared_ptr<TexturedModel> treeModel2 = AssetManager::getModel("lowPolyTree2");
    std::vector<std::shared_ptr<TexturedModel>> treeModels = {treeModel, treeModel2};
    for (int i = 0; i < treeCount; ++i) {
        glm::vec3 treePos;
        bool validPos = false;

        // versuche zufällige Position, bis Abstand stimmt oder max Versuche erreicht
        int attempts = 0;

        while (!validPos && attempts < maxAttempts) {
            treePos = tilePos;
            treePos.x += random.randomFloat(-hexRadius * 0.5f, hexRadius * 0.5f);
            treePos.z += random.randomFloat(-hexRadius * 0.5f, hexRadius * 0.5f);

            validPos = true;
            for (const auto& otherTree : entitiesOnTile) {
                if (glm::distance(treePos, otherTree->getPosition()) < minDistance) {
                    validPos = false;
                    break;
                }
            }
            attempts++;
        }

        if (!validPos) continue; // zu viele Versuche, überspringen

        int treeModelIndex = random.randomInt(0, static_cast<int>(treeModels.size()-1));
        auto treeEntity = std::make_shared<Entity>(treeModels[treeModelIndex], treePos, 0, 0, 0, 1.f);
        mapEntities.push_back(treeEntity);
        entitiesOnTile.push_back(treeEntity);
    }
    return entitiesOnTile;
}
