#include "lvgl/lvgl.h" // IWYU pragma: keep
#include "miniaudio/miniaudio.h"
#include <stdio.h>
#include <unistd.h>
#include "screen.h"
#include "pm3-lvgl.h"

#ifdef LV_TARGET_FB
#include "nfc.h"
#endif

lv_display_t *display;
uint32_t idle_time;

pthread_mutex_t lvgl_mutex = PTHREAD_MUTEX_INITIALIZER;

ma_result result;
ma_engine engine;

void key_pressed(lv_event_t *event)
{
	lv_key_t key = lv_indev_get_key(lv_indev_active());
	printf("%u\n", key);
	pthread_mutex_lock(&lvgl_mutex);
	screen_response("Valid until 1:09pm", "$2.50", 0, 2000);
	pthread_mutex_unlock(&lvgl_mutex);
	ma_engine_play_sound(&engine, "assets/hop_adult.wav", NULL);
}

void read_card(uint8_t status, uint8_t *version, uint16_t version_size,
	       uint8_t *data, uint16_t data_size)
{
	pthread_mutex_lock(&lvgl_mutex);
	screen_response("Valid until 1:09pm", "$2.50", 0, 2000);
	pthread_mutex_unlock(&lvgl_mutex);
	ma_engine_play_sound(&engine, "assets/hop_adult.wav", NULL);
}

int main(int argc, char *argv[])
{
	result = ma_engine_init(NULL, &engine);
	if (result != MA_SUCCESS) {
		return -1;
	}

	lv_init();
#ifdef LV_TARGET_FB
	display = lv_linux_fbdev_create();
	lv_linux_fbdev_set_file(display, "/dev/fb0");

	pthread_t nfc_thread;
	nfc_init("/dev/ttymxc3");
	pthread_create(&nfc_thread, NULL, nfc_handle, read_card);
#else
	display = lv_x11_window_create("LVGL X11 Simulation", 800, 480);
	lv_obj_remove_flag(lv_scr_act(), LV_OBJ_FLAG_SCROLLABLE);
	lv_x11_inputs_create(display, NULL);
	lv_obj_add_event_cb(lv_screen_active(), key_pressed, LV_EVENT_KEY,
			    NULL);
#endif

	screen_create(lv_screen_active());
	lv_group_add_obj(lv_group_get_default(), lv_screen_active());

	while (true) {
		/* Returns the time to the next timer execution */
		pthread_mutex_lock(&lvgl_mutex);
		idle_time = lv_timer_handler();
		pthread_mutex_unlock(&lvgl_mutex);
		usleep(idle_time * 1000);
	}
}
