import spidev
from .util import print_gdo_state, sleep, get_addr, dump_regs, debug, GDO0_PIN, GDO2_PIN
from .receive import rx_data_rf
from .transmit import transmit_packet
from .common import reset, setup_spi, setup_gpio, read_register, test_read_write_reg, init_cc_2500, write_reg, SRES, SNOP, MARCSTATE, VERSION



def menu():
    print("\nMenu")
    print("1: Read Reg by name")
    print("2: Write reg hex value by name")
    print("3: Dump registers")
    print("4: rx_data_rf")
    print("5: transmit_packet")
    print("6: Run Read+Write test")
    print("7: Print GDO state")
    print("0: Quit")


if __name__ == "__main__":
    setup_gpio(GDO0_PIN, GDO2_PIN)
    print_gdo_state(GDO0_PIN, GDO2_PIN)
    spi = setup_spi()
    reg_name = ""
    reg_hex_val = ""
    try:

        reset(spi)
        test_read_write_reg(spi)
        init_cc_2500(spi)
        stop = False
        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, True)
            elif cmd == 4:
                while(True):
                    rx_data_rf(spi)
            elif cmd == 5:
                transmit_packet(spi)
            elif cmd == 6:
                res = test_read_write_reg(spi, True)
                print("Test result : "+str(res))
            elif cmd == 7:
                print_gdo_state(GDO0_PIN, GDO2_PIN)
            else:
                print("Invalid command")
    finally:
        print("Closing SPI...")
        sleep(0.1)
        spi.close()
        sleep(0.1)
