/* Blinker
   Copyright 2011-2019 Stefan Schuermans <stefan@blinkenarea.org>
   Copyleft GNU public license - http://www.gnu.org/copyleft/gpl.html
   a blinkenarea.org project */

#ifndef BLINKER_PHONEEXTENSION_IMPL_H
#define BLINKER_PHONEEXTENSION_IMPL_H

#include <string>

#include "Directory.h"
#include "File.h"
#include "Module.h"
#include "NameFile.h"
#include "Phone.h"
#include "PhoneExtension.h"

namespace Blinker {

/**
 * @brief constructor
 * @param[in] phone owning phone object
 * @param[in] name extension name (i.e. phone number)
 * @param[in] dirBase base directory
 */
template<typename ADDR, typename SOCK>
Phone<ADDR, SOCK>::Extension::Extension(Phone &phone, const std::string &name,
                               const Directory &dirBase):
  m_phone(phone),
  m_name(name),
  m_fileTarget(dirBase.getFile("target"))
{
  // set up
  getTarget();
}

/// destructor
template<typename ADDR, typename SOCK>
Phone<ADDR, SOCK>::Extension::~Extension()
{
  // remove extension from extension map
  m_phone.m_extMap.erase(m_name);
}

/// check for update of configuration
template<typename ADDR, typename SOCK>
void Phone<ADDR, SOCK>::Extension::updateConfig()
{
  // target file was modified -> re-get target operator interface to connect to
  if (m_fileTarget.checkModified())
    getTarget();
}

/// (re-)get target operator interface to connect to
template<typename ADDR, typename SOCK>
void Phone<ADDR, SOCK>::Extension::getTarget()
{
  // remove old extension information from extension map
  m_phone.m_extMap.erase(m_name);

  // get new module name from file
  m_fileTarget.update();

  // add new module name to extension map
  if (m_fileTarget.m_valid)
    m_phone.m_extMap[m_name] = m_fileTarget.m_obj.m_str;
}

} // namespace Blinker

#endif // #ifndef BLINKER_PHONEEXTENSION_IMPL_H

