######
# LEAVE THESE IMPORTS!
######
import functions
import time

######
# config values
######

SERIAL_PORT = '/dev/ttyUSB0'
BAUD_RATE = 9600

LENGTH = 10
REPEAT = 10
DELAY = 10

###
# ^ = pullup, v = pulldown
###
triggers = [
    ['-', False],  #0
    ['^', False],  #1
    ['-', False],  #2
    ['-', False],  #3
    ['-', False],  #4
    ['-', False],  #5
    ['-', False],  #6
    ['-', False],  #7
]

###
# name, enabled, string to match
###
conditions = [
    ['rdy', False, "", 'setup_buttons'],
    ['ok', False, "", 'button_ok'],
    ['dash', False, "", 'button_dash'],
    ['spce', False, "", 'button_space'],
    ['dot', False, "", 'button_dot'],
    ['check', False, "", 'echo_trigger_state'],
    ["Flag", True, "TS{", "stop_glitch"],
]

######
# Custom functions
######
def setup_buttons():
    functions.run_output_low(0, 3000)
    functions.run_output_low(1, 3000)
    functions.run_output_low(2, 3000)
    functions.run_output_low(3, 3000)

def button_ok():
    functions.run_output_high(0, 15000000)  # Can also run_output_low() if needed
    functions.set_trigger_value(0, True)
    functions.run_output_low(0, 3000)

    last_state = functions.get_trigger_value(0)
    start_time = time.time()

    while True:
        current_state = functions.get_trigger_value(0)

        # Detect rising edge: 0 → 1
        if last_state == 0 and current_state == 1:
            functions.set_trigger_value(0, False)
            functions.add_text("[code check complete]")
            break

        # Exit if 1 second has elapsed
        if time.time() - start_time >= 1.0:
            functions.add_text("[timeout: no input detected within 1 second]")
            break

        last_state = current_state
        time.sleep(0.01)  # Polling interval (10 ms)


def button_dash():
    functions.run_output_high(1, 1500000) ## can also run_output_low() if need too
    functions.run_output_low(1, 3000)

def button_space():
    functions.run_output_high(2, 1500000) ## can also run_output_low() if need too
    functions.run_output_low(2, 3000)

def button_dot():
    functions.run_output_high(3, 1500000) ## can also run_output_low() if need too
    functions.run_output_low(3, 3000)


def echo_trigger_state():
    for channel in range(8):
        state = functions.get_trigger_value(channel)
        if state == 1:
            functions.add_text(f"Channel {channel}: HIGH")
        else:
            functions.add_text(f"Channel {channel}: LOW")

def stop_glitch():
    elapsed = functions.get_glitch_elapsed()

    functions.set_trigger_value(1, False)
    functions.set_uart_switch(False)

    functions.glitching_switch(False)
    functions.add_text(f"[auto] glitching stopped (elapsed: {elapsed})")  