import importlib
import time
import os
import sys
import traceback

import serial
import scene

start_addr = 1

with serial.Serial("/dev/ttyUSB0", 500000) as ser:

    payload = bytearray(512)

    FPS = 50
    if len(sys.argv) > 1:
        FPS = int(sys.argv[1])
    
    FRAME_TIME = 1 / FPS
    t = 0
    
    def sync():
        # wait for sync
        while True:
            b = ser.readline()
            if b.strip() == b"Sync.":
                return
            
    sync()

    print("initial sync.")

    last_edit_timestamp = os.stat(scene.__file__).st_mtime_ns
    while True:
        
        loop_start = time.time()
        
        try:
            timestamp = os.stat(scene.__file__).st_mtime_ns
            if timestamp > last_edit_timestamp:
                print("[importlib.reload]")
                importlib.reload(scene)
                last_edit_timestamp = timestamp
            scene.display(t, payload)
        except Exception:
            traceback.print_exc()
        
        ser.write(payload)
        ser.flush()
        
        response = ser.readline()
        if response.strip() != b"Ack.":
            print(f"received bad response: {response!r}")
            sync()
            continue

        t += FRAME_TIME
        t %= 1
        
        loop_time = time.time() - loop_start
        if loop_time < FRAME_TIME:
            time.sleep(FRAME_TIME - loop_time)
        else:
            print("loop took too long!")
            
        print(f"loop time: {1000 * loop_time:0.2f}ms busy, {1000 * (time.time() - loop_start):0.2f}ms total")

    # print(ser.read_all())
