#include "GameKitLoop.h"

namespace GameKit {

Loop::~Loop() { stop(); }

bool Loop::start(uint32_t tickMs, Scene* targetScene) {
    stop();
    if (targetScene == nullptr || tickMs == 0) return false;
    scene = targetScene;
    periodMs = tickMs;
    lastTickMs = lv_tick_get();
    timer = lv_timer_create(onTimer, tickMs, this);
    return timer != nullptr;
}

void Loop::stop() {
    if (timer != nullptr) {
        lv_timer_delete(timer);
        timer = nullptr;
    }
    scene = nullptr;
    periodMs = 0;
    lastTickMs = 0;
}

void Loop::onTimer(lv_timer_t* timer) {
    auto* loop = static_cast<Loop*>(lv_timer_get_user_data(timer));
    if (loop == nullptr || loop->scene == nullptr) return;
    const uint32_t now = lv_tick_get();
    uint32_t dt = loop->periodMs;
    if (loop->lastTickMs != 0) dt = now - loop->lastTickMs;
    loop->lastTickMs = now;
    loop->scene->onTick(Tick { dt, now });
    loop->scene->render();
}

} // namespace GameKit
