/* Blinker
   Copyright 2011-2019 Stefan Schuermans <stefan@blinkenarea.org>
   Copyleft GNU public license - http://www.gnu.org/copyleft/gpl.html
   a blinkenarea.org project */

#include <stdlib.h>
#include <string>

#include <BlinkenLib/BlinkenFrame.h>

#include "Directory.h"
#include "File.h"
#include "InStreamFile.h"
#include "Mgrs.h"
#include "Module.h"
#include "OutStreamFile.h"
#include "RateFile.h"
#include "RateLimiter.h"
#include "StreamRecv.h"
#include "Time.h"

namespace Blinker {

/**
 * @brief constructor
 * @param[in] name module name
 * @param[in] mgrs managers
 * @param[in] dirBase base directory
 */
RateLimiter::RateLimiter(const std::string &name, Mgrs &mgrs,
                         const Directory &dirBase):
  Module(name, mgrs, dirBase),
  m_fileInStream(dirBase.getFile("instream"), mgrs.m_streamMgr),
  m_fileMaxRate(dirBase.getFile("maxrate")),
  m_fileOutStream(dirBase.getFile("outstream"), mgrs.m_streamMgr),
  m_last(Time::now() - Time(1))
{
  // set up
  getMaxRate();
  m_fileInStream.setStreamRecv(this);
}

/// virtual destructor
RateLimiter::~RateLimiter()
{
  // clean up
  m_fileInStream.setStreamRecv(NULL);
}

/// check for update of configuration
void RateLimiter::updateConfig()
{
  // stream name or frame rate file was modified -> re-get stream or frame rate
  if (m_fileInStream.checkModified())
    m_fileInStream.update();
  if (m_fileMaxRate.checkModified())
    getMaxRate();
  if (m_fileOutStream.checkModified())
    m_fileOutStream.update();
}

/// callback when requested time reached
void RateLimiter::timeCall()
{
  // try to send current frame to output stream
  sendFrame();
}

/**
 * @brief set current frame
 * @param[in] stream stream name
 * @param[in] pFrame current frame (NULL for none)
 */
void RateLimiter::setFrame(const std::string &stream, stBlinkenFrame *pFrame)
{
  procFrame(pFrame);
  (void)stream; // unused
}

/// (re-)get maximum frame rate to limit to
void RateLimiter::getMaxRate()
{
  // read maximum frame rate from file
  m_fileMaxRate.update();

  // send current frame to output stream
  sendFrame();
}

/// send current frame to output stream
void RateLimiter::sendFrame()
{
  // get current frame from input stream and process it
  procFrame(m_fileInStream.getCurFrame());
}

/**
 * @brief process frame
 * @param[in] pFrame frame to process (NULL for none)
 */
void RateLimiter::procFrame(stBlinkenFrame *pFrame)
{
  // get current time
  Time now = Time::now();

  // get minimum time between two frames
  Time minDelta(1); // default to 1 fps
  if (m_fileMaxRate.m_valid)
    minDelta.fromFloatSec(1.0f / m_fileMaxRate.m_obj.m_rate);

  // minimum time not yet elapsed
  if (now - m_last < minDelta) {
    // schedule callback when minimum time has elapsed
    m_mgrs.m_callMgr.requestTimeCall(this, m_last + minDelta);
    // do not forward anything now
    return;
  }

  // no frame or no valid frame rate -> pass "no frame"
  if (!pFrame || !m_fileMaxRate.m_valid) {
    m_last = now; // save time of last forwarded "no frame"
    m_fileOutStream.setFrame(NULL);
    return;
  }

  // pass frame to output stream
  m_last = now; // save time of last forwarded frame
  m_fileOutStream.setFrame(pFrame);
}

} // namespace Blinker

