/* 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 "Sync.h"
#include "SyncFile.h"
#include "SyncMgr.h"

namespace Blinker {

/**
 * @brief constructor from path
 * @param[in] path path to file
 * @param[in] syncMgr sync stream manager
 */
SyncFile::SyncFile(const std::string &path, SyncMgr &syncMgr):
  NameFile(path),
  m_syncMgr(syncMgr),
  m_pSync(NULL)
{
  update();
}

/**
 * @brief constructor from basic file
 * @param[in] file basic file object
 * @param[in] syncMgr sync stream manager
 */
SyncFile::SyncFile(const File &file, SyncMgr &syncMgr):
  NameFile(file),
  m_syncMgr(syncMgr),
  m_pSync(NULL)
{
  update();
}

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

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

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

/// unreference sync stream
void SyncFile::unref()
{
  if (m_pSync) {
    m_syncMgr.unrefSync(m_obj.m_str);
    m_pSync = NULL;
  }
}

/// reference sync stream
void SyncFile::ref()
{
  if (m_valid)
    m_pSync = &m_syncMgr.refSync(m_obj.m_str);
}

} // namespace Blinker

