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

namespace Blinker {

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

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

/// destructor
InSyncFile::~InSyncFile()
{
  detach();
  // unreferencing sync stream happens in destructor of SyncFile
}

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

/**
 * @brief set sync stream receiver
 * @param[in] pSyncRecv sync stream reciver (NULL if none)
 */
void InSyncFile::setSyncRecv(SyncRecv *pSyncRecv)
{
  detach();
  m_pSyncRecv = pSyncRecv;
  attach();
}

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

/// attach to sync stream
void InSyncFile::attach()
{
  if (m_pSync && m_pSyncRecv)
    m_pSync->attach(m_pSyncRecv);
}

/// detach from sync stream
void InSyncFile::detach()
{
  if (m_pSync && m_pSyncRecv)
    m_pSync->detach(m_pSyncRecv);
}

} // namespace Blinker

