//-----------------------------------------------------------------------------
///
/// \brief  A PWM output
///
///         [...]
///
/// \date   20141204
/// \author Maximilian Seesslen <mes@seesslen.net>
///
//-----------------------------------------------------------------------------


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


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

#if defined (MCU_PLATFORM_STM32)
   #include <HALWrapper/stm32_gpio.h>
#endif

#include <biwak/pwm.hpp>
#include <biwak/linux/pwm.hpp>
#include <biwak/output.hpp>
#include <biwak/timer.hpp>
#include <lepto/log.h>
#include <biwak/exception.h>
#include <QAbstractSlider>
#include <biwak/linux/boardgui.h>


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


class CPwmDimpl
{
   friend class CPwmLine;
   
   private:
      QAbstractSlider* m_slider=nullptr;
   
   public:
      CPwmDimpl(const char* label)
      {
         CBoardGui *gui=CBoardGui::instance();
         if(gui)
         {
            m_slider=gui->createPwm(label);
            m_slider->setMaximum(1000);
         }
      }
};

/// \brief  Le contructeur
///
CPwmLine::CPwmLine(const SPwmLineConfig &configData, CTimer &timer )
   :m_timer(timer)
   ,m_eTimerChannel(configData.eTimerChannel)
   #if IS_ENABLED( CONFIG_BIWAK_HOLD_PWM_VALUE )
   ,m_pwmValue{ 0 }
   #endif
{
   m_pDimpl=new CPwmDimpl( configData.label );
   
   m_timer.setOutputChannel( m_eTimerChannel, 500 );
   m_timer.startTimerPwm(m_eTimerChannel);

   m_timer.setMode(eTimerModePWM);
   return;
}


CPwmLine::~CPwmLine()
{
   return;
}


void CPwmLine::setPwmValue(int permilliValue)
{
   #if IS_ENABLED( CONFIG_BIWAK_HOLD_PWM_VALUE )
   m_pwmValue=permilliValue;
   #endif

   m_timer.setOutputChannel(m_eTimerChannel, permilliValue);
   m_timer.startTimerPwm(m_eTimerChannel);
   
   if(m_pDimpl)
   {
      if( m_pDimpl->m_slider )
      {
         m_pDimpl->m_slider->setValue(permilliValue);
      }
   }

   return;
}


void CPwmLine::setPwmDmaValues(const uint32_t *buffer, int size)
{
   m_timer.setOutputChannel(m_eTimerChannel, 1000/2);
   //m_timer.setOutputChannel(m_eTimerChannel, 0);
   m_timer.setMasterConfig();
   m_timer.startDmaPwm(m_eTimerChannel, buffer, size);

   return;
}


void CPwmLine::restartPwmDmaValues(const uint32_t *buffer, int size)
{
   m_timer.startDmaPwm(m_eTimerChannel, buffer, size);

   return;
}

#if 0
void CPwmLine::eventLoop( )
{

}
#endif

void CPwmLine::setDmaChannel(CDmaChannel *dmaChannel)
{
   m_timer.setDmaChannel(dmaChannel);

   return;
}


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