#include <AssetManager/AssetManager.hpp>
#include <filesystem>
#include <Animation/Animation.hpp>
#include <Utilities/Utilities.hpp>

#define DECL_ANIMATION(name, fps) Animation Animation::name(#name, 1000/(fps))
#include <Animation/AnimationList.hpp>

Animation::Animation(const char *name, uint32_t frameDuration) :
    name(name),
    frameDuration(frameDuration)
{}

void Animation::load(std::atomic<unsigned int> &tasksDone)
{
    static std::atomic<unsigned int> ignoredTasksDone;

    int i;
    for (i=1;;i++)
    {
        std::string framePath = assets.resolve(formatString("animations/$+/$+.png", name, i));
        if (!std::filesystem::exists(framePath))
        {
            break;
        }

        std::shared_ptr<Material> mat = std::make_shared<Material>();
        mat->load(framePath, ignoredTasksDone);
        frames.push_back(mat);
    }

    if (frames.size() == 0)
    {
        crash(formatString("No frames found for animation '$+'!", name));
    }

    tasksDone++;
}

Material& Animation::getCurrentFrame()
{
    uint32_t frameNum = SDL_GetTicks() / frameDuration;
    return *frames[frameNum % frames.size()];
}