//
// Created by sebastian on 04.08.26.
//

#include "AnimationSystem.h"

#include <map>

#include "components/TransformAnimationComponent.h"
#include "ecs/standardComponents/TransformComponent.h"

namespace engine::animation {
    void animation::AnimationSystem::update(float deltaTime) {
        std::vector<engine::Entity> toRemove;
        for (auto& [entity, animation] : m_registry.getPool<TransformAnimationComponent>()) {
            animation.time += deltaTime;

            while (animation.nextMarkerIndex < animation.markers.size() && animation.markers[animation.nextMarkerIndex].time <= animation.time) {
                animation.markers[animation.nextMarkerIndex].callback();
                animation.nextMarkerIndex++;
            }

            auto& transform = m_registry.getComponent<TransformComponent>(entity);

            if (!animation.position.keys.empty()) {
                transform.m_position = evaluate(animation.position, animation.time);
            }
            if (!animation.rotation.keys.empty()) {
                transform.m_rotation = evaluate(animation.rotation, animation.time);
            }
            if (!animation.scale.keys.empty()) {
                transform.m_scale = evaluate(animation.scale, animation.time);
            }

            if (animation.time >= animation.duration) {
                if (animation.loop) {
                    animation.time = 0.f;
                    animation.nextMarkerIndex = 0;
                } else {
                    if (animation.onFinished) {
                        animation.onFinished();
                    }
                    animation.finished = true;
                    toRemove.push_back(entity);
                }
            }
        }

        for (auto entity : toRemove) {
            m_registry.removeComponent<TransformAnimationComponent>(entity);
        }
    }
} // engine