#ifndef _TOUCH_TSC2007_H_
#define _TOUCH_TSC2007_H_
//----------------------------------------------------------------------------
///
/// \brief  An TI TSC2007 resistiv touch controller
///
//----------------------------------------------------------------------------


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


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

#include <biwak/input.hpp>
#include <biwak/touch.h>
#include <biwak/i2c_slave.h>
#include <biwak/touch_calibration.h>
#include <lepto/ring.h>

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




/// \brief  An TI TSC2007 resistiv touch controller
class CTouchTsc2007: public CTouch
{
   private:
      CI2c &m_bus;
      CInput &m_input;
      CI2cSlave m_device;
      CTouchCalibration m_calibration;
      lrtimer_t   m_debounceTimer;
      
      static constexpr int CMD_SETUP=0xB0;
      static constexpr int CMD_READ_X=0xC0;
      static constexpr int CMD_READ_Y=0xD0;
      static constexpr int CMD_READ_Z1=0xE0;
      static constexpr int CMD_READ_Z2=0xF0;
      // Debounce: 50ms too less; 100ms quite good
      static constexpr int DEBOUNCE_MSEC=80;

      enum EState
      {
         eIdle,
         eHit,
         eHitEvent,
         //ePressDebounce,
         ePressed,
         eEnterReleaseDebounce,
         eReleaseDebounce,
         eReleased,

      } m_state = eIdle;
      int m_xRaw=0;
      int m_yRaw=0;
      int m_zRaw=0;
      int m_z1Raw=0;
      int m_z2Raw=0;
      lrtimer_t m_timerReadout;

   public:
      SEvent previousEvent{ };
      //CRing<SEvent> events;
      CSignal <void, const SEvent> signalEvent;
      CTouchTsc2007(CI2c &bus, CInput &input)
      :m_bus(bus)
      ,m_input(input)
      ,m_device(m_bus, 0x48)
      ,m_calibration( )
      ,m_timerReadout(0)
      {
         init();
         #if defined ( BIWAK_USE_INPUT_SIGNAL )
         m_input.interruptSignal.connect( this, &CTouchTsc2007::slotTouchPressed );
         #else
         #endif
      }
      ~CTouchTsc2007()
      {

      }
      void init()
      {
         //int i1;
         //m_device.i2cWriteData( CMD_SETUP , &i1, 0);
      }
      void readTouch( int &xRaw, int &yRaw, int &z1Raw, int &z2Raw);
      void readTouch( ) { readTouch( m_xRaw, m_yRaw, m_z1Raw, m_z2Raw); };
      void setTouch( int xRaw, int yRaw, int z1Raw, int z2Raw)
      {
         m_xRaw=xRaw;
         m_yRaw=yRaw;
         m_z1Raw=z1Raw;
         m_z2Raw=m_z2Raw;
      }
      void slotTouchPressed(bool value);
      void eventLoop(bool value=false, bool override=false);
      CTouchCalibration &calibration()
      {
         return(m_calibration);
      }
      bool readInput()
      {
         return( m_input.getValue() );
      }
};


//---fin----------------------------------------------------------------------
#endif // ? ! _TOUCH_TSC2007_H_
