//
// Created by sebastian on 24.12.25.
//

#include "GameLayer.h"

#include "../engine/platform/glfw/InputManager.h"
#include "../engine/renderer/Renderer.h"
#include "../engine/renderer/loader/OBJLoader.h"
#include "../engine/renderer/model/TexturedModel.h"
#include "../engine/renderer/textures/ModelTexture.h"
#include "../engine/toolbox/MathUtils.h"
#include "../engine/layer/entities/Light.h"
#include "hexWorld/HexModelFactory.h"
#include "hexWorld/MapGenerator.h"

GameLayer::GameLayer() :texturedModel(0,0) //Platzhalter, echtes Model kommt in onAttach
{
}

void GameLayer::onAttach()
{
    texturedModel = *OBJLoader::loadModel("assets/dragon/dragon.obj", "assets/dragon/dragon.png", loader);
    entity = std::make_unique<Entity>(Entity(std::make_shared<TexturedModel>(texturedModel), glm::vec3(0,0,-25), 0,0,0, 1.f));
    camera = std::make_unique<Camera>();
    light = std::make_unique<Light>(glm::vec3(0,10,0), glm::vec3(1,1,1));
    mousePicker = std::make_unique<MousePicker>(renderer->getProjectionMatrix(), MathUtils::createViewMatrix(*camera));

    //Map Generation
    hexModelDefault = std::make_shared<TexturedModel>(HexModelFactory::createTexturedHexModel(loader, 1.0f, RessourceType::NONE));
    hexModelWood = std::make_shared<TexturedModel>(HexModelFactory::createTexturedHexModel(loader, 1.0f, RessourceType::WOOD));
    map = std::make_unique<Map>();
    MapGenerator::generateHexMap(*map, 10,10,1.f);
    printf("Generated Terrain with %lu Tiles!\n", map->tiles.size());
}

void GameLayer::onDetach()
{
    Layer::onDetach();
}

void GameLayer::onUpdate()
{
    mousePicker->update(*camera);
    //printf("Mouse Ray: %f, %f, %f\n", mousePicker->getCurrentRay().x, mousePicker->getCurrentRay().y, mousePicker->getCurrentRay().z);
    glm::vec3 moveDir = glm::vec3(0,0,0);
    if (InputManager::isKeyPressed(GLFW_KEY_W)) moveDir.z -= 1.0f;
    if (InputManager::isKeyPressed(GLFW_KEY_S)) moveDir.z += 1.0f;
    if (InputManager::isKeyPressed(GLFW_KEY_A)) moveDir.x -= 1.0f;
    if (InputManager::isKeyPressed(GLFW_KEY_D)) moveDir.x += 1.0f;



    entity->increaseRotation(0,1,0);
    camera->move(moveDir, 0.5f);

    renderer->submitEntity(entity.get());

    for (HexTile& tile : map->tiles) {
        glm::vec3 intersectionPoint;
        bool highlight = tile.intersect(camera->getPosition(), mousePicker->getCurrentRay(), intersectionPoint);
        tile.isHighlighted = highlight;
    }

    std::vector<HexRenderData> terrainRenderData = map->getTerrainRenderData(hexModelDefault, hexModelWood);


    for (auto& renderData : terrainRenderData) {
        renderer->submitTerrainTile(&renderData);
    }

    renderer->render(*light, *camera);
}


