import grovepi
import time
import threading
from sensors.lock import grove_lock
from shared.logging import log

button = 2
button_switch_state = 0
grovepi.pinMode(button, "INPUT")

button_callback = None

def read_button_state():
    if not grove_lock.acquire(timeout=0.05):
        return None
    try:
        return grovepi.digitalRead(button)
    except Exception as e:
        log(f"BTN Error: {e}")
        return None
    finally:
        grove_lock.release()

def monitor_button():
    global button_switch_state
    last_button_state = button_switch_state
    
    while True:
        time.sleep(0.04) 

        current_state = read_button_state()
        
        if current_state is not None:
            if current_state == 1 and last_button_state == 0:
                if button_callback:
                    button_callback()
            last_button_state = current_state

def start_button_monitoring_thread():
    threading.Thread(target=monitor_button, daemon=True).start()

def set_callback(callback):
    global button_callback
    button_callback = callback