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

#ifndef COLORRACE_ANIMATIONSYSTEM_H
#define COLORRACE_ANIMATIONSYSTEM_H
#include "components/TransformAnimationComponent.h"
#include "ecs/EntityRegistry.h"
#include "glm/glm.hpp"
namespace engine::animation {
    class AnimationSystem {
    public:
        explicit AnimationSystem(EntityRegistry& registry) : m_registry(registry) {}
        void update(float deltaTime);
    private:
        EntityRegistry& m_registry;

        template<typename T>
        T evaluate(const AnimationTrack<T>& track, float time) {
            Keyframe<T> a;
            Keyframe<T> b;
            findSurroundingKeys(track, time, a, b);

            if (a.time == b.time) return a.value;

            float localT = (time - a.time) / (b.time - a.time);
            float easedT = a.easingFunction(localT);
            return glm::mix(a.value, b.value, easedT);
        }

        template<typename T>
        void findSurroundingKeys(const AnimationTrack<T>& track, float time, Keyframe<T>& a, Keyframe<T>& b) {
            if (track.keys.size() == 1) {
                a = b = track.keys.front();
                return;
            }

            if (time <= track.keys.front().time) {
                a = b = track.keys.front();
                return;
            }

            if (time >= track.keys.back().time) {
                a = b = track.keys.back();
                return;
            }

            for (size_t i = 1; i < track.keys.size(); ++i) {
                if (track.keys[i - 1].time <= time && track.keys[i].time >= time) {
                    a = track.keys[i - 1];
                    b = track.keys[i];
                    return;
                }
            }
        }

    };
} // engine

#endif //COLORRACE_ANIMATIONSYSTEM_H
