from micropython import const  # NOQA
import display_driver_framework

_WIDTH = const(480)
_HEIGHT = const(320)

_BUFFER_SIZE = _WIDTH * _HEIGHT * 3
import lcd_bus  # NOQA

print("Intializing LCD Bus")
bus = lcd_bus.SDLBus(flags=0)

print("Creating buffers")
buf1 = bus.allocate_framebuffer(_BUFFER_SIZE, 0)
buf2 = bus.allocate_framebuffer(_BUFFER_SIZE, 0)

import lvgl as lv  # NOQA

import sdl_display  # NOQA

print("Initializing LVGL")
lv.init()
print("Creating Display")
display = sdl_display.SDLDisplay(
    data_bus=bus,
    display_width=480,
    display_height=320,
    frame_buffer1=buf1,
    frame_buffer2=buf2,
    color_space=lv.COLOR_FORMAT.RGB888
)
print(display)
print("Initializing display")
display.init()

import sdl_pointer

print("Creating SDL pointer")
mouse = sdl_pointer.SDLPointer()
print(mouse)

print("Starting task handler")
import task_handler
th = task_handler.TaskHandler()

print("Activating screen")
scrn = lv.screen_active()
print("Setting screen style")
scrn.set_style_bg_color(lv.color_hex(0x000000), 0)

# Button
btn = lv.button(scrn)
btn.set_pos(10, 10)
btn.set_size(120, 50)
btn_label = lv.label(btn)
btn_label.set_text("Button")
g_btn_count = 0

def btn_event_cb(e: lv.event_t):
    btn = e.get_target_obj()
    label = btn.get_child(0)
    if e.get_code() == lv.EVENT.CLICKED:
        global g_btn_count 
        g_btn_count += 1
        label.set_text(f"Button: {g_btn_count}")
    
btn.add_event_cb(btn_event_cb, lv.EVENT.ALL, None)
