// sprites.h
#pragma once

#include "lib.h"
#include "include/raylib.h"

struct SpriteAnimation {
    u8 loop;
    u8 total_frames;
};

struct SpriteAnimationPlayback {
    f32 time_elapsed;
    u8 row;
    u8 total_frames;
    u8 current_frame;
    u8 loop;
};

void PlayAnimation(int animation, SpriteAnimation *anims, SpriteAnimationPlayback *playback);
void TickSpriteAnimations(SpriteAnimationPlayback *playbacks, int len);
bool IsAnimationFinished(SpriteAnimationPlayback playback);

inline void PlayAnimation(int animation, SpriteAnimation *anims, SpriteAnimationPlayback *playback) {
    playback->time_elapsed = 0.0f;
    playback->current_frame = 0;
    playback->row = animation;
    playback->total_frames = anims[animation].total_frames;
    playback->loop = anims[animation].loop;
}

void TickSpriteAnimations(SpriteAnimationPlayback *playbacks, int len) {
    const f32 anim_speed = 1.0f / 10.0f;
    for (int i = 0; i < len; i++) {
        SpriteAnimationPlayback *playback = &playbacks[i];
        playback->time_elapsed += GetFrameTime();
        if (playback->time_elapsed >= anim_speed) {
            playback->time_elapsed = 0.0f;
            playback->current_frame++;
            if (playback->current_frame >= playback->total_frames) {
                if (playback->loop) {
                    playback->current_frame = 0;
                }
            }
        }
    }
}

inline bool IsAnimationFinished(SpriteAnimationPlayback playback) {
    return playback.current_frame == playback.total_frames;
}
