//----------------------------------------------------------------------------
///
/// \file   test_fader.cpp
///
/// \brief  Tests for the fader class, used to control PWM
///
/// \date   20241010
/// \author Maximilian Seesslen <mes@seesslen.net>
///
//----------------------------------------------------------------------------


//---Documentation------------------------------------------------------------


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


//---General--------------------------

#if defined ( CATCH_V3 )
   #include <catch2/catch_test_macros.hpp>
#elif defined ( CATCH_V2 )
   #include <catch2/catch.hpp>
#elif defined ( CATCH_V1 )
   #include <catch/catch.hpp>
#else
   #error "Either 'catch' or 'catch2' has to be installed"
#endif

#include <biwak/fader.h>
#include <lepto/imago.hpp>

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

#define TEST_ALL
#define STOP_ON_FAIL

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


TEST_CASE( "Fader", "[default]" ) {

   CFader fader;
   fader.updateTime(0, 800, 1);
   
   auto eventLoop = [ &fader ] ( void )
   {
      biwakEventLoop();
      fader.eventLoop();
      usleep(100);
      return;
   };
   
   CImago< typeof( eventLoop) > imago( eventLoop );
   
   SECTION( "rising" )
   {
      REQUIRE ( fader.current() == 0 );
      fader.setTarget(800);
      imago.waitTimeMs( MSECS_PER_SEC / 2 );
      REQUIRE ( imago.approximately(fader.current(), 400, 25) == 400 );
      
      REQUIRE ( fader.isActive() == true );
      imago.waitTimeMs( MSECS_PER_SEC / 2 );
      REQUIRE ( imago.approximately(fader.current(), 800, 25) == 800 );
      imago.waitTimeMs( MSECS_PER_SEC / 128 );
      REQUIRE ( fader.current() == 800 );
      REQUIRE ( fader.isActive() == false );
      
      fader.setTarget(0);
      fader.finish();
      REQUIRE ( fader.current() == 0 );
   }
   
   SECTION( "half return" )
   {
      //      1/8     1/4           1/2                           1s
      // [     |       |      |      |                           ]800
      //      100     200    300    400
      REQUIRE ( fader.current() == 0 );
      fader.setTarget(800);
      imago.waitTimeMs( MSECS_PER_SEC / 2 );
      REQUIRE ( imago.approximately(fader.current(), 400, 25) == 400 );
      fader.setTarget(200);
      imago.waitTimeMs( MSECS_PER_SEC / 8 );
      REQUIRE ( imago.approximately(fader.current(), 300, 25) == 300 );
      imago.waitTimeMs( MSECS_PER_SEC / 8 );
      REQUIRE ( imago.approximately(fader.current(), 200, 25) == 200 );
   }
   
   SECTION( "immideate" )
   {
      fader.setTarget(0);
      fader.finish();
      REQUIRE ( fader.current() == 0 );
      fader.updateTime(0, 800, 0);
      fader.setTarget( 1000 );
      fader.eventLoop();
      REQUIRE ( fader.current() == 1000 );
   }
}


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