#include "w5500.h"

#include "ch32v003fun.h"

static inline uint8_t SPI_is_RX_empty() { return SPI1->STATR & SPI_STATR_RXNE; }

static inline void SPI_wait_not_busy() {
  while ((SPI1->STATR & SPI_STATR_BSY) != 0);
}

static inline uint8_t SPI_transfer(uint8_t data) {
  while (!(SPI1->STATR & SPI_STATR_TXE));
  // SPI_wait_not_busy();
  SPI1->DATAR = data;

  while (!(SPI1->STATR & SPI_STATR_RXNE));
  return SPI1->DATAR;
}

void W5500_Select(void) {
  GPIOA->BCR = (1 << 4);  // Set PA4 (CS) low
  // Delay_Ms(2);
}

void W5500_Unselect(void) {
  GPIOA->BSHR = (1 << 4);  // Set PA4 (CS) high
  // Delay_Ms(2);
}

uint8_t W5500_ReadByte() {
  return SPI_transfer(0xFF);  // dummy byte to init read
}

void W5500_WriteByte(uint8_t byte) { SPI_transfer(byte); }

void W5500_ReadBuff(uint8_t* buffer, uint16_t len) {
  for (uint16_t i = 0; i < len; i++) {
    buffer[i] = W5500_ReadByte();
  }
}

void W5500_WriteBuff(uint8_t* buffer, uint16_t len) {
  for (uint16_t i = 0; i < len; i++) {
    W5500_WriteByte(buffer[i]);
  }
}