#ifndef SPI_H
#define SPI_H

#include <stm32f4xx.h>
#include <stdint.h>
#include <stdbool.h>
#include "pin.h"

typedef enum {
  SPI_FRAME_8_BIT = 0,
  SPI_FRAME_16_BIT = 1,
} spi_frame_format_t;

typedef enum {
  SPI_MSB_FIRST = 0,
  SPI_LSB_FIRST = 1,
} spi_frame_orientation_t;

typedef struct {
  SPI_TypeDef* periph;
  uint8_t idx;
  pin_t csn;
} spi_t;

void spi_init(spi_t* spi, pin_t csn, SPI_TypeDef* peripheral, uint8_t idx);

void spi_master_configure_speed(spi_t *spi,
                                uint8_t divider);

void spi_master_configure(spi_t *spi, bool sw_nss, bool clock_polarity,
                          bool clock_phase, spi_frame_orientation_t orientation, spi_frame_format_t format);
void spi_master_enable(spi_t* spi, bool enable);

uint16_t spi_transmit(spi_t* spi, uint16_t* data, uint16_t size);
uint16_t spi_receive(spi_t *spi, uint16_t *buffer, uint16_t max_size);

bool spi_can_transmit(spi_t* spi);
uint16_t spi_can_receive(spi_t* spi);

void spi_pulse_csn(spi_t *spi);

bool spi_enable_interrupt(spi_t* spi, bool tx, bool rx);

#endif // SPI_H
