from util import *
import time

def burst_read(spi, addr, length):
    """Read multiple bytes"""
    READ_SINGLE = get_addr["READ_SINGLE"]
    READ_BURST = get_addr["READ_BURST"]
    return spi.xfer2([addr | READ_SINGLE | READ_BURST] + [0x00] * length)



def read_fifo(spi):
    # Burst read RX FIFO
    READ_BURST = get_addr("READ_BURST")
    RXFIFO = get_addr("RXFIFO")
    fifo = spi.xfer2([RXFIFO | READ_BURST] + [0x00]*64)  # Max 64 bytes
    return fifo[1:]


def receive_packet(spi):
    # Flush RX FIFO
    SFRX = get_addr("SFRX")
    strobe(spi, SFRX)  # SFRX

    SRX = get_addr( "SRX")
    # Go into RX mode
    strobe(spi, SRX)  # SRX

    # Wait for data (use GDO0 in real app)
    time.sleep(0.5)

    # Check RXBYTES
    RXBYTES = get_addr( "RXBYTES")
    rx_bytes = read_register(spi, RXBYTES) & 0x7F
    if rx_bytes == 0:
        print("No data received.")
        return None

    # Read data
    # RXFIFO = get_addr("RXFIFO")
    data = read_fifo(spi)  # 0x3F = RX FIFO
    print(f"Received: {data}")
    return data
