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

namespace Blinker {

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

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

/// destructor
StreamFile::~StreamFile()
{
  unref();
}

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

/// update, i.e. (re-)read file and reference new stream
void StreamFile::update()
{
  unref();
  NameFile::update();
  ref();
}

/// unreference stream
void StreamFile::unref()
{
  if (m_pStream) {
    m_streamMgr.unrefStream(m_obj.m_str);
    m_pStream = NULL;
  }
}

/// reference stream
void StreamFile::ref()
{
  if (m_valid)
    m_pStream = &m_streamMgr.refStream(m_obj.m_str);
}

} // namespace Blinker

