#include "game/entities/explosions.hpp"

#include <utility>  // Para std::cmp_less

#include "core/rendering/sprite/animated_sprite.hpp"  // Para AnimatedSprite

class Texture;  // lines 4-4

// Actualiza la lógica de la clase (time-based)
void Explosions::update(float delta_time) {
    for (auto& explosion : explosions_) {
        explosion->update(delta_time);
    }

    // Vacia el vector de elementos finalizados
    freeExplosions();
}

// Dibuja el objeto en pantalla
void Explosions::render() {
    for (auto& explosion : explosions_) {
        explosion->render();
    }
}

// Añade texturas al objeto
void Explosions::addTexture(int size, const std::shared_ptr<Texture>& texture, const std::vector<std::string>& animation) {
    textures_.emplace_back(size, texture, animation);
}

// Añade una explosión
void Explosions::add(int x, int y, int size) {
    const auto INDEX = getIndexBySize(size);
    explosions_.emplace_back(std::make_unique<AnimatedSprite>(textures_[INDEX].texture, textures_[INDEX].animation));
    explosions_.back()->setPos(x, y);
}

// Vacia el vector de elementos finalizados
void Explosions::freeExplosions() {
    if (!explosions_.empty()) {
        for (int i = explosions_.size() - 1; i >= 0; --i) {
            if (explosions_[i]->animationIsCompleted()) {
                explosions_.erase(explosions_.begin() + i);
            }
        }
    }
}

// Busca una textura a partir del tamaño
auto Explosions::getIndexBySize(int size) -> int {
    for (int i = 0; std::cmp_less(i, textures_.size()); ++i) {
        if (size == textures_[i].size) {
            return i;
        }
    }

    return 0;
}