
#include "io.hpp"
#include "config.hpp"

#include <iostream>
#include <fstream>
#include <sstream>
#include <map>

/*/ C
#include <stdio.h>
#include <stdlib.h> // atoi needed
#include <string.h>
*/

using namespace std;

void config::read_config(const std::string & settings_path)
{
   std::ifstream settings_file(settings_path);
   std::string line;

   LOG_STREAM << "config::read_config()" << endl;

   if (settings_file.fail())
   {
      LOG_STREAM << "config file does not exist. Default options used." << endl;

      return;
   }


   while (std::getline(settings_file, line))
   {
      std::istringstream iss(line);
      std::string id, eq, val;

      if (std::getline(iss, id, '='))
      {
         if (std::getline(iss, val))
         {
            if (m_settings.find(id) != m_settings.end())
            {
               if (val.empty())
               {
                  LOG_STREAM << "config " << id.c_str()
                     << " is empty. Keeping default " << m_settings[id].c_str() << endl;
               }
               else
               {
                  m_settings[id] = val;
                  LOG_STREAM << "config " << id.c_str()
                     <<" read as " << m_settings[id].c_str() << endl;
               }
            }
            else
            {
               //Not present in map
               LOG_STREAM << "Setting "<< id.c_str() << " not defined, ignoring it" << endl;
               continue;
            }
         }
         else
         {
            // Comment line, skiping it
            continue;
         }
      }
      else
      {
         //Empty line, skipping it
         continue;
      }
   }
}

