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):
    SFRX = get_addr("SFRX")
    RXBYTES = get_addr("RXBYTES")
    SRX = get_addr("SRX")
    
    # Flush RX FIFO
    strobe(spi, SFRX)
    time.sleep(0.5)  # 1 ms delay to allow flush
    # Go into RX mode
    strobe(spi, SRX) 

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

    # Check RXBYTES
    
    timeout = time.time() + 2  # 2-second timeout
    while time.time() < timeout:
        rx_bytes = read_register(spi, RXBYTES) & 0x7F
        if rx_bytes > 0:
            data = read_fifo(spi)
            print(f"Received: {data}")
            return data
        time.sleep(0.01)

print("Timeout: no data received.")
