#include "WEBServerManager.h"
#include "definition.h"

#define DEBUG_WEB_SERVER_MANAGER(...) do {} while(0)
//#define DEBUG_WEB_SERVER_MANAGER(...) do { Serial.printf(__VA_ARGS__); Serial.println();} while(0)

WEBServerManager::WEBServerManager(SDCardManager &sdCardManager) : _sdCardManager(&sdCardManager), _webServer(80, &sdCardManager, 10)
{

}

WEBServerManager::~WEBServerManager()
{

}

boolean WEBServerManager::init(void)
{
    CFGDictionary<CFGParameterValue> *serverCfg = _sdCardManager->getCFGFile(SERVER_CFG_FILE);
    boolean toReturn(true);
    
    //We were not able to read the config file, so we apply default parameters
    if(!serverCfg)
    {
        DEBUG_WEB_SERVER_MANAGER("serverCfg is NULL, applying default parameters !");
        _webServer.setWWWDir(WWW_DIR);
        _webServer.enableTCPKeepAlive(15,5,5);
        _webServer.start();
        _isServiceEnabled = true;
        return toReturn;
    }

    //We managed to read the config file, now we can apply it !
    if((*serverCfg)("WEB_ENABLED"))
    {
        if((*serverCfg)("WEB_ENABLED")->booleanValue())
        {
            _isServiceEnabled = true;

            if((*serverCfg)("WEB_PORT"))
            {
                DEBUG_WEB_SERVER_MANAGER("WEB_PORT is %u", (*serverCfg)("WEB_PORT")->uintValue());
                _webServer.setPort((*serverCfg)("WEB_PORT")->uintValue());
            }
            
            if((*serverCfg)("WEB_MAX_CLIENT"))
            {
                DEBUG_WEB_SERVER_MANAGER("WEB_MAX_CLIENT is %u", (*serverCfg)("WEB_MAX_CLIENT")->uintValue());
                _webServer.setMaxClient((*serverCfg)("WEB_MAX_CLIENT")->uintValue());
            }

            if((*serverCfg)("WEB_WWW_DIR"))
            {
                DEBUG_WEB_SERVER_MANAGER("WEB_WWW_DIR is %s", (*serverCfg)("WEB_WWW_DIR")->stringValue());
                _webServer.setWWWDir((*serverCfg)("WEB_WWW_DIR")->stringValue());
            }

            _webServer.start();
        }
        else
        {
            _webServer.stop();
            _isServiceEnabled = false;
        }
    }
    else
    {
        DEBUG_WEB_SERVER_MANAGER("WEB_ENABLED is NULL !");
        toReturn = false; 
    }

    return toReturn;
}

boolean WEBServerManager::isEnabled(void) const
{
    return _isServiceEnabled;
}

WEBServer<WEBClient> &WEBServerManager::getWEBServer(void)
{
    return _webServer;
}