/* 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 "Scaler.h"
#include "Size.h"
#include "StreamRecv.h"

namespace Blinker {

/**
 * @brief constructor
 * @param[in] name module name
 * @param[in] mgrs managers
 * @param[in] dirBase base directory
 */
Scaler::Scaler(const std::string &name, Mgrs &mgrs,
                 const Directory &dirBase):
  Module(name, mgrs, dirBase),
  m_fileInStream(dirBase.getFile("instream"), mgrs.m_streamMgr),
  m_fileSize(dirBase.getFile("size")),
  m_fileOutStream(dirBase.getFile("outstream"), mgrs.m_streamMgr)
{
  // set up
  getSize();
  m_fileInStream.setStreamRecv(this);
}

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

/// check for update of configuration
void Scaler::updateConfig()
{
  // stream name or size file was modified -> re-get stream or size
  if (m_fileInStream.checkModified())
    m_fileInStream.update();
  if (m_fileSize.checkModified())
    getSize();
  if (m_fileOutStream.checkModified())
    m_fileOutStream.update();
}

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

/// (re-)get size to scale to
void Scaler::getSize()
{
  // read size from size file
  m_fileSize.update();

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

/// send current frame to output stream
void Scaler::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 Scaler::procFrame(stBlinkenFrame *pFrame)
{
  int width, height;
  stBlinkenFrame *pProcFrame;

  // no frame or no size -> pass "no frame"
  if (!pFrame || !m_fileSize.m_valid) {
    m_fileOutStream.setFrame(NULL);
    return;
  }
  width = m_fileSize.m_obj.m_width;
  height = m_fileSize.m_obj.m_height;

  // size matches -> pass frame directly
  if (BlinkenFrameGetWidth(pFrame) == width &&
      BlinkenFrameGetHeight(pFrame) == height ) {
    m_fileOutStream.setFrame(pFrame);
    return;
  }

  // clone frame
  pProcFrame = BlinkenFrameClone(pFrame);
  if (!pProcFrame) {
    m_fileOutStream.setFrame(NULL);
    return;
  }

  // scale frame
  BlinkenFrameScale(pProcFrame, height, width);

  // pass processed frame to output stream
  m_fileOutStream.setFrame(pProcFrame);

  // free cloned frame
  BlinkenFrameFree(pProcFrame);
}

} // namespace Blinker

