#ifndef ANIMATING_HPP_
#define ANIMATING_HPP_

#include <Utilities/Extern.hpp>
#include <functional>
#include <optional>

template<typename T>
class Animating
{
public:
    typedef std::function<T(T, T)> Interpolator;

private:
    std::optional<T> cached;
    Interpolator interpolate;
    Uint64 cacheTimestamp;

public:
    Animating(Interpolator interpolate) :
        interpolate(interpolate)
    {}

    virtual ~Animating() = default;

    T sample(T target)
    {
        if (!cached.has_value() || SDL_GetTicks() - cacheTimestamp > 1000)
        {
            cached = target;
            cacheTimestamp = SDL_GetTicks();
        }
        else
        {
            Uint64 frames = (SDL_GetTicks() - cacheTimestamp) / 20;
            for (Uint64 i = 0; i < frames; i++)
            {
                cached = interpolate(*cached, target);
            }

            if (frames != 0)
            {
                cacheTimestamp = SDL_GetTicks();
            }
        }

        return *cached;
    }
};

#endif