import spidev
from util import *
from receive import receive_packet
debug = True

def menu():
    print("\nMenu")
    print("1: Read Reg by name")
    print("2: Write reg hex value by name")
    print("3: Dump registers")
    print("4: Poll for packets")
    print("0: Quit")

if __name__ == "__main__":
    spi = spidev.SpiDev()
    spi.open(0, 0)  # Bus 0, CE0 (Pin 24)
    spi.max_speed_hz = 500000  # Safe start speed
    spi.mode = 0b00  # SPI mode 0
    stop = False

    print("Sending SRES (reset)...")
    spi.xfer2([SRES])
    sleep(0.1)

    print("Sending SNOP (no-op)...")
    status = spi.xfer2([SNOP])[0]
    print(f"Status byte: 0x{status:02X}")

    print("Reading VERSION register...")
    version = read_register(spi, VERSION)
    print(f"CC2500 VERSION register: 0x{version:02X}")  

    init_regs(spi)
    sleep(0.1)

    test_read_write_reg(spi)

    reg_name = ""
    reg_hex_val = ""
    try:
        while not stop:
            menu()
            cmd = int(input("$: "))
            if cmd == 0:
                stop=True
            elif cmd == 1:
                reg_name = input("Register name: ")
                addr = get_addr(reg_name)
                value = read_register(spi,addr)
                print("Address: " + hex(addr)+ ", Value: " + hex(value) +" == " + str(value))
            elif cmd == 2:
                reg_name = input("Register name: ")
                addr = get_addr(reg_name)
                value = int(input("New Register value (hex): "),16)
                write_reg(spi, addr, value)
                sleep(0.1)
                value_check = read_register(spi,addr)
                print("Updated Value: " + hex(value) +" == " + str(value))
            elif cmd == 3:
                dump_regs(spi)
            elif cmd == 4:
                while True:
                    receive_packet(spi)
                    sleep(0.2)
            else:
                print("Invalid command")
    finally:
        spi.close()
