#include <stdint.h>
#include <stdio.h>

#include "app_util_platform.h"
#include "nrf_drv_twi.h"
#include "twi.h"

//Not used:
//#include "nrf_delay.h"
//#include "boards.h"
//#include "app_error.h"

/* TWI */
#define TWI_INSTANCE_ID 0
#define SCL_PIN         8
#define SDA_PIN         9

/* TWI instance. */
static const nrf_drv_twi_t m_twi = NRF_DRV_TWI_INSTANCE(TWI_INSTANCE_ID);

/**
 * @brief TWI initialization.
 */
void twi_init (void)
{
  ret_code_t err_code;
  const nrf_drv_twi_config_t twi_config = 
  {
    .scl                = SCL_PIN,
    .sda                = SDA_PIN,
    .frequency          = NRF_TWI_FREQ_100K,
    .interrupt_priority = APP_IRQ_PRIORITY_HIGH,
  };
  err_code = nrf_drv_twi_init(&m_twi, &twi_config, NULL, NULL);
  APP_ERROR_CHECK(err_code);
  nrf_drv_twi_enable(&m_twi);
}

uint8_t twi_read(uint8_t address)
{
  ret_code_t err_code;
  uint8_t buffer;
  err_code = nrf_drv_twi_rx(&m_twi, address, &buffer, sizeof(buffer));
  //if (err_code == NRF_SUCCESS){}
  return buffer;
}

void twi_read_multi(uint8_t address, uint8_t* buffer, uint8_t size)
{
  ret_code_t err_code;
  err_code = nrf_drv_twi_rx(&m_twi, address, buffer, size);
  //if (err_code == NRF_SUCCESS){}
}
void twi_write(uint8_t address, uint8_t input)
{
  ret_code_t err_code;
  uint8_t buffer = input; // RAR - need to assign input data to buffer
  err_code = nrf_drv_twi_tx(&m_twi, address, &buffer, sizeof(buffer), false);
  //if (err_code == NRF_SUCCESS){}
}
  // RAR - register write must be a single transacion
void twi_reg_write(uint8_t address, uint8_t reg_address, uint8_t input)
{
  ret_code_t err_code;
  uint8_t buffer[2] = {reg_address, input};
  err_code = nrf_drv_twi_tx(&m_twi, address, buffer, sizeof(buffer), false);
  //if (err_code == NRF_SUCCESS){}
}
/** @} */
