/* 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 "File.h"
#include "InStreamFile.h"
#include "Stream.h"
#include "StreamFile.h"
#include "StreamMgr.h"
#include "StreamRecv.h"

namespace Blinker {

/**
 * @brief constructor from path
 * @param[in] path path to file
 * @param[in] streamMgr stream manager
 */
InStreamFile::InStreamFile(const std::string &path, StreamMgr &streamMgr):
  StreamFile(path, streamMgr),
  m_pStreamRecv(NULL)
{
  update();
}

/**
 * @brief constructor from basic file
 * @param[in] file basic file object
 * @param[in] streamMgr stream manager
 */
InStreamFile::InStreamFile(const File &file, StreamMgr &streamMgr):
  StreamFile(file, streamMgr),
  m_pStreamRecv(NULL)
{
  update();
}

/// destructor
InStreamFile::~InStreamFile()
{
  detach();
  // unreferencing stream happens in destructor of StreamFile
}

/**
 * @brief assignment operator
 * @param[in] file basic file object
 */
const InStreamFile & InStreamFile::operator=(const File &file)
{
  detach();
  StreamFile::operator=(file);
  attach();
  return *this;
}

/**
 * @brief set stream receiver
 * @param[in] pStreamRecv stream reciver (NULL if none)
 */
void InStreamFile::setStreamRecv(StreamRecv *pStreamRecv)
{
  detach();
  m_pStreamRecv = pStreamRecv;
  attach();
}

/// update, i.e. (re-)read file and attach to new stream
void InStreamFile::update()
{
  detach();
  StreamFile::update();
  attach();
}

/**
 * @brief get current frame
 * @return current frame (NULL for none)
 */
stBlinkenFrame * InStreamFile::getCurFrame() const
{
  if (m_pStream)
    return m_pStream->getCurFrame();
  else
    return NULL;
}

/// attach to stream
void InStreamFile::attach()
{
  if (m_pStream && m_pStreamRecv)
    m_pStream->attach(m_pStreamRecv);
}

/// detach from stream
void InStreamFile::detach()
{
  if (m_pStream && m_pStreamRecv)
    m_pStream->detach(m_pStreamRecv);
}

} // namespace Blinker

