#include "particle_manager.hpp"

#include "../../log.hpp"

#include <format>

using namespace game::resource::xml;

namespace game::state::play
{
  void ParticleManager::spawn(Character& character, const std::string& label, glm::vec2 position)
  {
    for (auto* particle : character.particleSchema.get_all(Schema::Element::PARTICLE))
    {
      if (!particle || particle->typeString != label) continue;
      if (!particle->anm2Entry.is_valid()) return;

      auto& anm2 = particle->anm2Entry.anm2;
      auto animationIndex = anm2.animationMap.contains(particle->animation) ? anm2.animationMap.at(particle->animation)
                                                                            : anm2.defaultAnimationID;
      Entity entity{anm2, position, Entity::PLAY, 0.0f, animationIndex};
      entity.entityType = PARTICLE;
      entity.isRemoveOnAnimationEnd = true;

      particles.push_back(std::move(entity));
      return;
    }

    logger.warning(std::format("Particle not found: {}", label));
  }

  void ParticleManager::update()
  {
    for (int i = 0; i < (int)particles.size();)
    {
      particles[i].update();
      if (particles[i].isToBeDeleted)
      {
        particles.erase(particles.begin() + i);
        continue;
      }
      i++;
    }
  }

  void ParticleManager::render(resource::Shader& textureShader, resource::Shader& rectShader, Canvas& canvas)
  {
    for (auto& particle : particles)
      particle.render(textureShader, rectShader, canvas);
  }
}
