//-----------------------------------------------------------------------------
///
/// \brief  A LED output
///
///         An LED is just an output so we only set the type of output.
///
/// \date   20121107
/// \author Maximilian Seesslen <development@seesslen.net>
///
//-----------------------------------------------------------------------------


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


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

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


//---Implementation------------------------------------------------------------


/// \brief  Le contructeur
///
CLed::CLed(EGpioPeripheral _eGpioPeripheral, EGpioPin _eGpioPin)
   :COutput(_eGpioPeripheral, _eGpioPin) //  gpioModeLed
{
   m_blinkMode=nullptr;
}


/// \brief  Le contructeur
///
CLed::CLed(const char* label)
    :COutput(label)
{
   m_blinkMode=nullptr;
}


CLed::~CLed()
{

}

void CLed::setBlinkMode( SBlinkMode blinkMode )
{
   if( m_blinkMode == blinkMode )
      return;

   if( blinkMode != nullptr )
   {
      if( blinkMode[0] < BLINK_CODE_END )
      {
         setValue( blinkMode[0] == BLINK_CODE_ON ? true : false );
#if defined ( BIWAK_OUTPUT_SWITCH )
         m_blinkState=false;
#endif
         m_blinkMode=nullptr;
         return;
      }
   }
   m_blinkMode=blinkMode;
   blinkArrayPos=0;
   blinkerTimer=lrNow();
   
#if ! defined ( BIWAK_OUTPUT_SWITCH )
   bool m_blinkState;
#endif
   
   m_blinkState=( m_blinkMode != nullptr ) ? true : false;
   setValue( m_blinkState );
}

#if 0
/// \brief  Let the led blink
///
/// \param  stay: The function will not return and will blink permanently
void COutput::blink( bool stay /*=true*/)
{
   eventLoop();
   return;
}
#endif

/// \brief  Handles the predefined blink modes
///
///         Has to be called cyclic
void CLed::eventLoop( )
{
   if( m_blinkMode == nullptr )
      return;

   if( lrElapsedMSeconds( &blinkerTimer, m_blinkMode[blinkArrayPos] ) )
   {
      switchInvert();
      
      blinkArrayPos++;
      if( m_blinkMode[blinkArrayPos] < 0 )
      {
         // -1: restart at 0
         // -2: stop it. Caution: it will not automatically switch off
         if( m_blinkMode[blinkArrayPos] == BLINK_CODE_END )
         {
            m_blinkMode=nullptr;
         }
         
         blinkArrayPos=0;
      }
   }
   
   return;
}


//---fin-----------------------------------------------------------------------
