#include <tt_app.h>
#include <tt_lvgl_toolbar.h>

#define TICK_MS 25
lv_timer_t* gameTimer;

static void onTick(lv_timer_t* timer) {
    // 1. Retrieve the progress bar using the official getter function
    lv_obj_t* bar_progress = (lv_obj_t*) lv_timer_get_user_data(timer);
    int32_t current_val = lv_bar_get_value(bar_progress);
    

    // 4. Stop and delete the timer when it reaches 100
    if (current_val + 1 >= 100) {
        lv_bar_set_value(bar_progress, 0, LV_ANIM_ON);
    } else {
        lv_bar_set_value(bar_progress, current_val + 1, LV_ANIM_OFF);
    }
}

/**
 * Note: LVGL and Tactility methods need to be exposed manually from TactilityC/Source/tt_init.cpp
 * Only C is supported for now (C++ symbols fail to link)
 */
static void onShowApp(AppHandle app, void* data, lv_obj_t* parent) {
    lv_obj_t* toolbar = tt_lvgl_toolbar_create_for_app(parent, app);
    lv_obj_align(toolbar, LV_ALIGN_TOP_MID, 0, 0);

    lv_obj_t* label = lv_label_create(parent);
    lv_label_set_text(label, "Hello, world!\n(Adolfo Made It2!)");
    lv_obj_align(label, LV_ALIGN_CENTER, 0, 0);

    lv_obj_t* label2 = lv_label_create(parent);
    lv_label_set_text(label2, "Hello, There!");
    lv_obj_align(label2, LV_ALIGN_BOTTOM_MID, 0, 0);

     /* Progress bar */
    lv_obj_t* bar_progress = lv_bar_create(parent);
    lv_obj_set_size(bar_progress, lv_pct(80), 10);
    lv_bar_set_range(bar_progress, 0, 100);
    lv_bar_set_value(bar_progress, 50, LV_ANIM_ON);
    lv_obj_align(bar_progress, LV_ALIGN_CENTER, 0, -30);

    // Start game timer wiht the progress bar as user data 
    gameTimer = lv_timer_create(onTick, TICK_MS, bar_progress);
}

//on hide
static void onHideApp(AppHandle app, void* data) {
    if (gameTimer) {
        lv_timer_delete(gameTimer);
        gameTimer = NULL;
    }
}

int main(int argc, char* argv[]) {
    tt_app_register((AppRegistration) {
        .onShow = onShowApp,
        .onHide = onHideApp,

    });
    return 0;
}
