#include "ConnectivityManager.h"

ConnectivityManager::ConnectivityManager() : _error(0), _sdCardManager(NULL)
{
  persistent(false);
  WiFi.disconnect();
  WiFi.softAPdisconnect();
  
  if(!enableSTAAndAP(false))_error &= AP_AND_STA_ENABLED_ERR;
  if(!softAP("ESP8266SwissArmyBoard", NULL, 1, false, 8))_error &= AP_SETUP_ERR;
}

ConnectivityManager::ConnectivityManager(SDCardManager &sdCardManager) : _error(0), _sdCardManager(&sdCardManager)
{
  persistent(false);
  WiFi.disconnect();
  WiFi.softAPdisconnect();
  
  if(!enableSTAAndAP(false))_error &= AP_AND_STA_ENABLED_ERR;
  else
  {
    //SOFT AP PART
    CFGFileParser cfgFileParser(sdCardManager, AP_CFG_FILE);
    CFGDictionary<CFGParameterValue> *cfgDictionary = (CFGDictionary<CFGParameterValue> *) cfgFileParser.parseFile();
    if(cfgDictionary == NULL)
    {
      if(!softAP("ESP8266SwissArmyBoard", NULL, 1, false, 8))_error &= AP_SETUP_ERR;
    }
    else if((*cfgDictionary)("SSID") != NULL && (*cfgDictionary)("PASSWORD") != NULL && (*cfgDictionary)("CHANNEL") != NULL && (*cfgDictionary)("SSID_HIDDEN") != NULL && (*cfgDictionary)("AP_MAX_CONNECTION") != NULL && (*cfgDictionary)("ENABLED") != NULL)
    {
      if((*cfgDictionary)("ENABLED")->booleanValue())
      {
        if(!softAP((*cfgDictionary)("SSID")->stringValue(), strcmp((*cfgDictionary)("PASSWORD")->stringValue(),"") == 0 ? NULL:(*cfgDictionary)("PASSWORD")->stringValue(), (*cfgDictionary)("CHANNEL")->intValue(), (*cfgDictionary)("SSID_HIDDEN")->booleanValue(), (*cfgDictionary)("AP_MAX_CONNECTION")->intValue()))
          _error &= AP_SETUP_ERR;
      }
      delete cfgDictionary;
    }
  	else
  	{
  	  if(!softAP("ESP8266SwissArmyBoard", NULL, 1, false, 8))_error &= AP_SETUP_ERR;
  	  delete cfgDictionary;
  	}

    //STATION PART
    CFGFileParser cfgFileParserSTA(sdCardManager, STA_CFG_FILE);
    cfgDictionary = (CFGDictionary<CFGParameterValue> *) cfgFileParserSTA.parseFile();
    if(cfgDictionary != NULL)
    {
	    if((*cfgDictionary)("SSID") != NULL && (*cfgDictionary)("PASSWORD") != NULL && (*cfgDictionary)("ENABLED") != NULL)
	    {
        if((*cfgDictionary)("ENABLED")->booleanValue())
        {
  		    if(!begin((*cfgDictionary)("SSID")->stringValue(), (*cfgDictionary)("PASSWORD")->stringValue()))
  		      _error &= AP_SETUP_ERR;
        }
	    }
      delete cfgDictionary;
    }
  }
}

boolean ConnectivityManager::enableSTAAndAP(boolean enabled)
{
  return enableSTA(enabled) && enableAP(enabled);
}

boolean ConnectivityManager::isSTAEnabled()
{
  return (getMode() == WIFI_AP_STA || getMode() == WIFI_STA);
}

boolean ConnectivityManager::isAPEnabled()
{
  return (getMode() == WIFI_AP_STA || getMode() == WIFI_AP);
}

unsigned char ConnectivityManager::RSSIPercent()
{
  int RSSIdBm = RSSI();
  return COEF_RSSI * ((double)RSSIdBm - (double)MIN_RSSI);
}

unsigned char ConnectivityManager::getError() const
{
  return _error;
}
