/* 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_SETTINGFILE_IMPL_H
#define BLINKER_SETTINGFILE_IMPL_H

#include <fstream>
#include <string>

#include "File.h"
#include "SettingFile.h"

namespace Blinker {

/**
 * @brief constructor from path
 * @param[in] path path to file
 */
template<typename TYPE>
SettingFile<TYPE>::SettingFile(const std::string &path):
  File(path)
{
  update();
}

/**
 * @brief constructor from basic file
 * @param[in] file basic file object
 */
template<typename TYPE>
SettingFile<TYPE>::SettingFile(const File &file):
  File(file)
{
  update();
}

/**
 * @brief assignment operator
 * @param[in] file basic file object
 */
template<typename TYPE>
const SettingFile<TYPE> & SettingFile<TYPE>::operator=(const File &file)
{
  File::operator=(file);
  update();
  return *this;
}

/// update, i.e. (re-)read file
template<typename TYPE>
void SettingFile<TYPE>::update()
{
  std::string strSize;

  m_valid = getStr(strSize) && m_obj.fromStr(strSize);
}

/**
 * @brief get setting as string
 * @param[out] val setting read from file
 * @return if setting was successfully read from file
 */
template<typename TYPE>
bool SettingFile<TYPE>::getStr(std::string &val) const
{
  std::ifstream ifstrm(m_path.c_str(), std::ios::in);
  if (!ifstrm.is_open())
    return false;

  std::getline(ifstrm, val);
  if (ifstrm.fail())
    return false;

  ifstrm.close();

  return true;
}

} // namespace Blinker

#endif // #ifndef BLINKER_SETTINGFILE_IMPL_H

