import board
import time
time.sleep(5)
import usb_hid
import keypad
from analogio import AnalogIn
from adafruit_hid.consumer_control import ConsumerControl
from adafruit_hid.consumer_control_code import ConsumerControlCode
from adafruit_hid.keyboard import Keyboard
from adafruit_hid.keycode import Keycode


# ---------- POTENTIOMETER ----------

potentiometer = AnalogIn(board.GP28)
consumer_control = ConsumerControl(usb_hid.devices)

READ_TIME = 0.01
MIN_ADC = 272
MAX_ADC = 65368
MAX_VOL = 21
SAMPLES = 8
RAW_DEADBAND = 300

last_position = 0
last_raw = 0
last_read = time.monotonic()

def read_smooth(samples=SAMPLES):
    total = 0
    for _ in range(samples):
        total += potentiometer.value
    return total // samples

def clamp(val, lo, hi):
    if val < lo: return lo
    if val > hi: return hi
    return val

# Reset host volume to minimum
for _ in range(32):
    consumer_control.send(ConsumerControlCode.VOLUME_DECREMENT)

# ---------- KEYPAD ----------

# 3 rows, 4 columns
rows = (board.GP2, board.GP3, board.GP4)
cols = (board.GP5, board.GP6, board.GP7, board.GP8)

matrix = keypad.KeyMatrix(rows, cols)
keyboard = Keyboard(usb_hid.devices)

# Row-major order (left → right, top → bottom)
keymap = [
    Keycode.F1, Keycode.F2, Keycode.F3, Keycode.F4,
    Keycode.ONE, Keycode.TWO, Keycode.HOME, Keycode.PAGE_UP,
    Keycode.FIVE, Keycode.SIX, Keycode.END, Keycode.PAGE_DOWN
]

# ---------- MAIN LOOP ----------

while True:

    # ----- VOLUME KNOB -----
    if time.monotonic() - last_read > READ_TIME:

        raw_value = read_smooth()

        if abs(raw_value - last_raw) < RAW_DEADBAND:
            raw_value = last_raw
        last_raw = raw_value

        raw_value = clamp(raw_value, MIN_ADC, MAX_ADC)

        position = (raw_value - MIN_ADC) * MAX_VOL // (MAX_ADC - MIN_ADC)

        if position != last_position:
            while last_position < position:
                consumer_control.send(ConsumerControlCode.VOLUME_INCREMENT)
                last_position += 1
            while last_position > position:
                consumer_control.send(ConsumerControlCode.VOLUME_DECREMENT)
                last_position -= 1

        last_read = time.monotonic()

    # ----- KEYPAD -----
    event = matrix.events.get()
    if event and event.pressed:
        key_number = event.key_number
        if key_number < len(keymap):
            keyboard.press(keymap[key_number])
            keyboard.release_all()
