#include "game/scenes/frame_animator.hpp"

#include <algorithm>

namespace Scenes {

    FrameAnimator::FrameAnimator(int num_frames, int frame_ms, bool loop)
        : num_frames_(std::max(1, num_frames)),
          frame_ms_(std::max(1, frame_ms)),
          loop_(loop) {}

    void FrameAnimator::tick(int delta_ms) {
        if (finished_) {
            return;
        }
        elapsed_ms_ += delta_ms;
        while (elapsed_ms_ >= frame_ms_) {
            elapsed_ms_ -= frame_ms_;
            ++current_frame_;
            if (current_frame_ >= num_frames_) {
                if (loop_) {
                    current_frame_ = 0;
                } else {
                    current_frame_ = num_frames_ - 1;
                    finished_ = true;
                    return;
                }
            }
        }
    }

    void FrameAnimator::reset() {
        current_frame_ = 0;
        elapsed_ms_ = 0;
        finished_ = false;
    }

}  // namespace Scenes
