#ifndef CONFIGURATION_H
#define CONFIGURATION_H
//------------------------------------------------------
// Includes
//------------------------------------------------------
#include <iostream>
#include <fstream>
#include <string>

#include "./Constants.h"
#include "./Support.h"

//------------------------------------------------------
// Configurations
//------------------------------------------------------
char* CONF_TCP_SERVER_IP;
unsigned short int CONF_TCP_SERVER_PORT;
bool CONF_IS_LOOP_DATA;
bool CONF_IS_SERVER;
unsigned int CONF_PACKET_SLEEP_TIME;

string trim(string str)
{
   string drop = " ";
   string result = str.erase(str.find_last_not_of(drop) + 1);
   return result.erase(0, result.find_first_not_of(drop));
}

// Load initial configuration
void loadConfiguration()
{
   int foundConfigCount = 0;
   int requiredConfigCount = CONST_REQUIRED_CONFIG_COUNT; // UPDATE THIS WHEN ADDING NEW CONFIG PARAMETER

   string id;
   string value;
   ifstream configFile(CONST_CONFIG_FILE);

   if(configFile.is_open())
   {
      while(!configFile.eof())
      {
         getline(configFile, id);
         getline(configFile, value);

         id = trim(id);
         value = trim(value);

         if(id == "CONF_TCP_SERVER_IP")
         {
            CONF_TCP_SERVER_IP = strdup(value.c_str());
            foundConfigCount++;
         }
         else if(id == "CONF_TCP_SERVER_PORT")
         {
            CONF_TCP_SERVER_PORT = atoi(value.c_str());
            foundConfigCount++;
         }
         else if(id == "CONF_IS_LOOP_DATA")
         {
            CONF_IS_LOOP_DATA = (value == "true");
            foundConfigCount++;
         }
         else if(id == "CONF_IS_SERVER")
         {
            CONF_IS_SERVER = (value == "true");
            foundConfigCount++;
         }
         else if(id == "CONF_PACKET_SLEEP_TIME")
         {
            CONF_PACKET_SLEEP_TIME = (unsigned int)atoi(value.c_str());
            foundConfigCount++;
         }
      }

      if(foundConfigCount != requiredConfigCount)
      {
         ostringstream errorMsg;
         errorMsg << "Cannot load all configurations: Required: " << requiredConfigCount << " Found: " << foundConfigCount << "\n";
         logToFile("ERROR", "Configuration", errorMsg.str());
      }

      configFile.close();
   }
   else
   {
      ostringstream errorMsg;
      errorMsg << "Cannot open config file: " << CONST_CONFIG_FILE << "\n";
      logToFile("ERROR", "Configuration", errorMsg.str());
   }
}

#endif // CONFIGURATION_H
