import time
import ssd1306
from machine import Pin, I2C

# Constantes para el teclado
ROW_PINS = [12, 14, 27, 26]
COL_PINS = [25, 33, 32]
KEY_MAP = [
    ['1', '2', '3'],
    ['4', '5', '6'],
    ['7', '8', '9'],
    ['*', '0', '#']
]

# Constantes para el display
DISPLAY_SCL_PIN = 21
DISPLAY_SDA_PIN = 22
DISPLAY_WIDTH = 128
DISPLAY_HEIGHT = 64

# Variables globales
last_key_press = 0
debounce_time = 200  # ms
current_code = ""

# Inicializar pines del teclado
rows = [Pin(pin, Pin.OUT) for pin in ROW_PINS]
cols = [Pin(pin, Pin.IN, Pin.PULL_DOWN) for pin in COL_PINS]

# Llenar display
def fill_display(text):
    display.fill(0)
    display.text(text, 0, 5)
    display.show()

# Limpiar display
def clear_display():
    display.fill(0)
    display.show()

# Función de interrupción para el teclado
def handle_keypress(pin):
    global last_key_press, current_code
    current_time = time.ticks_ms()
    if current_time + last_key_press > debounce_time:
            for i, row in enumerate(rows):
                row.value(1)
                if pin.value():
                    key = KEY_MAP[i][cols.index(pin)]
                    print(i, row, key)
                    if key == '#':
                        current_code = ""  # Limpiar el código actual
                    else:
                        current_code += key
                    fill_display(current_code)
                    last_key_press = current_time
                    break
                row.value(0)   

# Configurar interrupciones para las columnas
for col in cols:
    col.irq(trigger=Pin.IRQ_RISING, handler=handle_keypress)

# Inicializar Display OLED
i2c = I2C(0, scl=Pin(DISPLAY_SCL_PIN), sda=Pin(DISPLAY_SDA_PIN))
display = ssd1306.SSD1306_I2C(DISPLAY_WIDTH, DISPLAY_HEIGHT, i2c)

# Mensaje inicial
fill_display("Listo")

# Mantener las filas en alto
for row in rows:
    row.value(1)

# Bucle principal
try:
    while True:
        time.sleep(1)  # Dormir para ahorrar energía, las interrupciones manejarán las pulsaciones
except KeyboardInterrupt:
    clear_display()
    print("Programa terminado")