#ifndef BIWAK_SPI_SLAVE_H_
#define BIWAK_SPI_SLAVE_H_
//----------------------------------------------------------------------------
///
/// \brief  Generic spi slave
///
///         See implementation files for further information.
///
/// \date   20160716
/// \author Maximilian Seesslen <mes@seesslen.net>
///
//----------------------------------------------------------------------------


//---Includes-----------------------------------------------------------------


//---Own------------------------------

#include <biwak/output.hpp>
#include <biwak/spi.hpp>

#define CS_ACTIVE          false
#define CS_INACTIVE        true
//#define CS_ENABLE_DELAY    10
//#define CS_DISABLE_DELAY   10
#define CS_ENABLE_DELAY_US    0
#define CS_DISABLE_DELAY_US   0
// #define BIWAK_NESTED_SPI_CHIPSELECT 1

#if ! defined CONFIG_BIWAK_NESTED_SPI_CHIPSELECT
   #define CONFIG_BIWAK_NESTED_SPI_CHIPSELECT            1
#endif


//---Declaration--------------------------------------------------------------


/**
 * @brief   Generic spi slave with chip select
 *
 *          The class controlls the chips select line. pulling the chip select
 *          line can be nested. In this case the chips select is not release
 *          every time but only when first level is left.
 */
class CSpiSlave
{

   private:
      CSpi     &m_spi;
      COutput  m_outputCS;

      //static int csEnableDelay;
      //static int csDisableDelay;

      #if IS_ENABLED( CONFIG_BIWAK_NESTED_SPI_CHIPSELECT )
         int m_csNestCount{};
      #endif

   public:

      CSpiSlave( CSpi &_spi, EGpioPeripheral eGpioPeripheralCS, EGpioPin eGpioPinCS );
      ~CSpiSlave();

      void chipSelect()
      {
         #if IS_ENABLED( CONFIG_BIWAK_NESTED_SPI_CHIPSELECT )
         if(!m_csNestCount)
         {
         #endif
            m_outputCS.setValue(CS_ACTIVE);
            //usleep(CS_ENABLE_DELAY);
         #if IS_ENABLED( CONFIG_BIWAK_NESTED_SPI_CHIPSELECT )
         }
         m_csNestCount++;
         #endif
      };
      void chipDeselect()
      {
         #if IS_ENABLED( CONFIG_BIWAK_NESTED_SPI_CHIPSELECT )
         m_csNestCount--;
         if(!m_csNestCount)
         {
         #endif
            m_outputCS.setValue(CS_INACTIVE);
            //usleep(CS_DISABLE_DELAY);
         #if IS_ENABLED( CONFIG_BIWAK_NESTED_SPI_CHIPSELECT )
         };
         #endif
      };

      CSpi &getSpi()
      {
         return(m_spi);
      }
      COutput &getCs()
      {
         return(m_outputCS);
      }
};


//---fin----------------------------------------------------------------------
#endif // ? ! BIWAK_SPI_SLAVE_H_
