//
// Created by sebastian on 02.08.26.
//

#include "PiecePresenter.h"


#include "LudoGameMode.h"
#include "core/animation/components/TransformAnimationComponent.h"
#include "ecs/standardComponents/MeshComponent.h"
#include "ecs/standardComponents/PickableComponent.h"
#include "ecs/standardComponents/TransformComponent.h"


void ludo::PiecePresenter::spawnPieces(const ludo::LudoGameState &state) {
    for (const auto& piece : state.getPieces()) {
        auto entity = m_registry.createEntity();
        const auto transform = engine::TransformComponent(
            m_layout.getWorldPosition(piece.color, piece.state, piece.position),
            {0,0,0},
            {0.334296f, 0.334296f, 0.334296f});
        m_registry.addComponent<engine::TransformComponent>(entity, transform);
        m_registry.addComponent<engine::MeshComponent>(entity, engine::MeshComponent(m_pieceModels[std::string(ludo::toString(piece.color))]));
        m_registry.addComponent<engine::PickableComponent>(entity, engine::PickableComponent());
        m_pieceEntities.push_back(entity);
    }
}

void ludo::PiecePresenter::onPieceMoved(const ludo::PieceMovedEvent &event, const ludo::LudoGameState &state) {
    const auto& piece = state.getPieces()[event.pieceIndex];
    auto target = m_layout.getWorldPosition(piece.color, piece.state, piece.position);
    auto entity = m_pieceEntities[event.pieceIndex];
    auto& transform = m_registry.getComponent<engine::TransformComponent>(entity);
    transform.m_position = target;
}

std::optional<int> ludo::PiecePresenter::getPieceIndex(std::optional<engine::Entity>::value_type entity) {
    auto it = std::ranges::find(m_pieceEntities, entity);
    if (it == m_pieceEntities.end()) return std::nullopt;
    return static_cast<int>(std::distance(m_pieceEntities.begin(), it));
}


