# code.py ## Workout Rest-Interval Helper (CircuitPython, Particle Argon)
import time
import os
import board
import analogio
import pwmio
import keypad
from tm1637 import TM1637

# CONFIG — adjust pins here if your wiring differs
CLK_PIN = board.A4        # TM1637 clock
DIO_PIN = board.A5        # TM1637 data   (swap A4/A5 if digits look scrambled)
POT_PIN = board.A0        # potentiometer wiper (try board.A1 if no response)
BUZZER_PIN = board.D4     # piezo buzzer  (try board.D5 if silent)
BUTTON_PIN = board.D2     # push button

# Some Grove button modules drive the line HIGH when pressed — flip this if so.
BUTTON_ACTIVE_HIGH = os.getenv("BUTTON_ACTIVE_HIGH", "0") == "1"

# Interval range: 0:15 ... 2:00 in 5s steps
MIN_SECONDS = 15
MAX_SECONDS = 120
STEP_SECONDS = 5
NUM_STEPS = (MAX_SECONDS - MIN_SECONDS) // STEP_SECONDS

BRIGHTNESS = int(os.getenv("DISPLAY_BRIGHTNESS", "5"))    # 0-7
BEEP_HZ = int(os.getenv("BEEP_HZ", "2300"))

display = TM1637(CLK_PIN, DIO_PIN, brightness=BRIGHTNESS)
pot = analogio.AnalogIn(POT_PIN)
buzzer = pwmio.PWMOut(BUZZER_PIN, frequency=BEEP_HZ, duty_cycle=0,
                      variable_frequency=True)
keys = keypad.Keys((BUTTON_PIN,), value_when_pressed=BUTTON_ACTIVE_HIGH,
                   pull=True)


def read_selected_seconds():
    """Average a few ADC samples and quantise to the nearest 5s step."""
    total = 0
    for _ in range(8):
        total += pot.value
    raw = total // 8
    step = (raw * NUM_STEPS + 32768) // 65535      # round to nearest step
    step = max(0, min(NUM_STEPS, step))
    return MIN_SECONDS + step * STEP_SECONDS


def beep_done():
    """Three short beeps spanning ~1 second."""
    for i in range(3):
        buzzer.frequency = BEEP_HZ
        buzzer.duty_cycle = 32768          # 50% -> tone on
        time.sleep(0.15)
        buzzer.duty_cycle = 0              # tone off
        if i < 2:
            time.sleep(0.20)


IDLE, RUNNING, PAUSED = range(3)
state = IDLE
remaining = 0
last_tick = 0.0
colon = True
last_pause_blink = 0.0
pause_visible = True

print("Workout helper ready. Turn the pot to set a rest interval, press to start.")

while True:
    event = keys.events.get()
    pressed = bool(event and event.pressed)
    now = time.monotonic()

    if state == IDLE:
        display.show_time(read_selected_seconds(), colon=True)
        if pressed:
            remaining = read_selected_seconds()
            last_tick = now
            colon = True
            display.show_time(remaining, colon=colon)
            state = RUNNING

    elif state == RUNNING:
        if now - last_tick >= 1.0:
            last_tick += 1.0
            remaining -= 1
            colon = not colon                      # blink the colon each second
            if remaining <= 0:
                display.show_time(0, colon=True)
                beep_done()
                state = IDLE
                continue
            display.show_time(remaining, colon=colon)
        if pressed:
            display.show_time(remaining, colon=True)   # steady colon = paused
            last_pause_blink = now
            pause_visible = True
            state = PAUSED

    elif state == PAUSED:
        if now - last_pause_blink >= 0.5:
            last_pause_blink = now
            pause_visible = not pause_visible
            if pause_visible:
                display.show_time(remaining, colon=True)
            else:
                display.clear()
        if pressed:
            display.show_time(remaining, colon=True)
            last_tick = now                            # resume cleanly
            state = RUNNING

    time.sleep(0.01)