#pragma once

#include "common.h"
#include "jtag.h"
#include "esplink.h"
#include "fw.h"

extern_c int fpga_program_spz(spz_stream *spz);
extern_c int fpga_reset(void);

extern_c esp_err_t fpga_service_init(void);
extern_c void fpga_service_enable(bool);

extern_c void fpga_timesync_trigger(void);

#define FPGA_CMD_IRQ(x)	((x) << 0)
#define FPGA_CMD_ACK(x)	((x) << 3)
#define FPGA_CMD_WR	(0 << 6)
#define FPGA_CMD_RD	(1 << 6)
#define FPGA_CMD_STAMP	(1 << 7) /* Save timestamp */

/* Internal bits, not sent over the wire: */
#define FPGA_CMD_NULL	(1 << 8) /* Don't skip an empty command */
#define FPGA_CMD_STATUS	(1 << 9) /* Include status in read command */

struct fpga_iov {
    unsigned int cmd;
    union {
	const volatile void *addr;
	uint32_t iaddr;
    };
    union {
	const void *wdata;
	void *rdata;
    };
    size_t len;
};

extern_c esp_err_t fpga_iov(const struct fpga_iov *iov, size_t niov);
extern_c esp_err_t fpga_io_write(unsigned int cmd, const volatile void *addr,
				 const void *data, size_t len);
extern_c esp_err_t fpga_io_read(unsigned int cmd, const volatile void *addr,
				void *data, size_t len);
extern_c uint32_t fpga_io_status(unsigned int cmd);
extern_c void fpga_enable_nce(void);
extern_c esp_err_t fpga_send_config(void);

struct esplink_head;
extern_c void esplink_init(void);
extern_c void esplink_start(const struct esplink_head *head);
extern_c void esplink_poll(void);

extern_c EventGroupHandle_t esplink_filled;

#define ELQUEUE_DL(n)	((n) << 1)
#define ELQUEUE_UL(n)	(((n) << 1) + 1)
#define ELWAIT_ONLINE	ELQUEUE_DL(EL_RB_COUNT)

static inline EventBits_t esplink_wait_for(EventBits_t queues, bool online)
{
    return xEventGroupWaitBits(esplink_filled,
			       queues | (online ? ELWAIT_ONLINE : 0),
			       0, pdTRUE, portMAX_DELAY) ^ ELWAIT_ONLINE;
}
