from .regs_addr import regs_addr
import RPi.GPIO as GPIO
import time
debug = True
GDO0_PIN=17
GDO2_PIN=27

def rr(spi, addr):
    READ_SINGLE = get_addr("READ_SINGLE")
    # Send address | 0x80 (read), then 0x00 dummy to clock in response
    response = spi.xfer2([READ_SINGLE | addr, 0x00])
    sleep(0.1)
    return response[1]

def print_gdo_state(GDO0_PIN=17, GDO2_PIN=27):
    gdo0 = GPIO.input(GDO0_PIN)  # Reads 1 or 0
    gdo2 = GPIO.input(GDO2_PIN)
    print(f"GDO0 (GPIO{GDO0_PIN}): {gdo0}, GDO2 (GPIO{GDO2_PIN}): {gdo2}")
    sleep(0.1) 

def digital_read(GDO_PIN: int):
    return GPIO.input(GDO_PIN)

def get_addr(name):
    addr = ""
    stop = False
    for reg_type, reg_data in regs_addr.items():
        for reg_name, reg_addr in reg_data.items():
            if reg_name == name:
                stop = True
                addr = reg_addr
    if stop == False:
        raise Exception("Failed to find address for "+name)
    return addr

def dump_regs(spi, cfgonly = False):
    if cfgonly:
        for reg_name, reg_addr in regs_addr["CONFIG_REGS"].items():
            name :str = reg_name
            value = rr(spi, reg_addr)
            print((name+":").ljust(15) +hex(value).ljust(4)+"\t"+str(value))
    else:
        for reg_type, reg_data in regs_addr.items():
            for reg_name, reg_addr in reg_data.items():
                name :str = reg_name
                value = rr(spi, reg_addr)
                print((name+":").ljust(15) +hex(value).ljust(4)+"\t"+str(value))

# def disable_crc(spi):
#     spi.xfer2([CONFIG_REGS["PKTCTRL0"], 0x01])

def sleep(t):
    return time.sleep(t)

def delay(t):
    """Delay for t milliseconds."""
    time.sleep(t / 1000.0)

def delayMicroseconds(t):
    """Delay for t microseconds."""
    time.sleep(t / 1_000_000.0)
