from machine import Pin, I2C
from ssd1306 import SSD1306_I2C
from game_input import TouchInput
from game import PracticeGame
from game_display import draw_game
from time import sleep, ticks_ms

# temp import
from time import sleep, ticks_us, ticks_diff

# OLED
i2c = I2C(1, scl=Pin(7), sda=Pin(6), freq=400000)
oled = SSD1306_I2C(128, 64, i2c)

# Input + game
buttons = TouchInput()
game = PracticeGame()

DISPLAY_INTERVAL_MS = 50
last_display = ticks_ms()

while True:

    # fast logic

    press = buttons.get_press()

    if press is not None:
        game.handle_press(press)

    game.update()


    # ---- slower path: OLED ----

    now = ticks_ms()

    if ticks_diff(now, last_display) >= DISPLAY_INTERVAL_MS:

        draw_game(oled, game)

        last_display = ticks_ms()
    
    sleep(0.001)


# counter = 0
# while True:
# 
#     loop_start = ticks_us()
# 
#     # -----------------
#     # Input timing
#     # -----------------
#     input_start = ticks_us()
# 
#     press = buttons.get_press()
# 
#     input_time = ticks_diff(
#         ticks_us(),
#         input_start
#     )
# 
#     if press is not None:
#         game.handle_press(press)
# 
#     game.update()
# 
#     # -----------------
#     # Display timing
#     # -----------------
#     display_start = ticks_us()
# 
#     draw_game(oled, game)
# 
#     display_time = ticks_diff(
#         ticks_us(),
#         display_start
#     )
# 
#     # -----------------
#     # Whole loop
#     # -----------------
#     loop_time = ticks_diff(
#         ticks_us(),
#         loop_start
#     )
# 
#     print(
#         "input:", input_time,
#         "display:", display_time,
#         "total:", loop_time
#     )
# 
#     sleep(0.001)
#     counter += 1
# 
#     if counter >= 20:
# 
#         print(
#             "input:", input_time,
#             "display:", display_time,
#             "total:", loop_time
#         )
# 
#         counter = 0
