#include "sd_mmc_spi_impl.h"
#include "hal_io.h"
#include "hal_spi_m_sync.h"

static struct io_descriptor* spi_inst = NULL;

int32_t sd_mmc_spi_impl_init(void)
{
	PORT->Group[SD_MMC_SPI_nCS_PORT].DIR.reg |= (1 << SD_MMC_SPI_nCS_PIN);
	PORT->Group[SD_MMC_SPI_nCS_PORT].OUT.reg |= (1 << SD_MMC_SPI_nCS_PIN);


	if(ERR_NONE != spi_m_sync_get_io_descriptor(&SPI_SD_MMC, &spi_inst))
	{
		return -1;
	}

	if(!spi_inst)
	{
		return -1;
	}

	spi_m_sync_enable(&SPI_SD_MMC);
	return 0;
}

int32_t sd_mmc_spi_impl_read(uint8_t* const bytes, uint16_t len)
{
	return io_read(spi_inst, bytes, len);
}

int32_t sd_mmc_spi_impl_write(const uint8_t* const bytes, uint16_t len)
{
	return io_write(spi_inst, bytes, len);
}

int32_t sd_mmc_spi_impl_select_device()
{
	PORT->Group[SD_MMC_SPI_nCS_PORT].OUT.reg &= ~(1 << SD_MMC_SPI_nCS_PIN);
	return 0;
}

int32_t sd_mmc_spi_impl_deselect_device()
{
	PORT->Group[SD_MMC_SPI_nCS_PORT].OUT.reg |= (1 << SD_MMC_SPI_nCS_PIN);
	return 0;
}

bool sd_mmc_spi_impl_check_cd()
{
	return PORT->Group[SD_MMC_SPI_CD_PORT].IN.reg & (1 << SD_MMC_SPI_CD_PIN);
}
