/*
 * This source file is part of KEOS (Free 3D Engine)
 * For the latest info, see http://www.keosengine.org/
 * E-mails : thierry.vouriot@keosengine.org, yeri@keosengine.org
 * 
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Lesser General Public License as published by the Free Software
 * Foundation; either version 2 of the License, or (at your option) any later
 * version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License along with
 * this program; if not, write to the Free Software Foundation, Inc., 59 Temple
 * Place - Suite 330, Boston, MA 02111-1307, USA, or go to
 * http://www.gnu.org/copyleft/lesser.txt.
 */

#include "KeosXMLConfigFile.h"
#include "KeosException.h"
#include "KeosString.h"
#include "KeosLogger.h"
#include "KeosRoot.h"
#include "../Extlibs/TinyXML/tinyxml.h"

namespace Keos {

    //-----------------------------------------------------------------------
    CXMLConfigFile::CXMLConfigFile()
    {
    }

    //-----------------------------------------------------------------------
    CXMLConfigFile::~CXMLConfigFile()
    {
        Clear();
    }

    //-----------------------------------------------------------------------
    void CXMLConfigFile::Clear(void)
    {
        m_Settings.clear();
    }

    //-----------------------------------------------------------------------
    bool CXMLConfigFile::Load(const String& strFilename)
    {
        TiXmlDocument doc( strFilename.c_str() );
	    bool bLoadOkay = doc.LoadFile();
        if ( !bLoadOkay )
	    {
            ILogger::Log("Cannot open config file \"%s\", default settings will be used !", strFilename.c_str());
		    return false;
	    }

        TiXmlNode* root = doc.RootElement();
        if ( !root )
	    {
            ILogger::Log("Invalid config file \"%s\" file, default settings will be used !", strFilename.c_str());
		    return false;
	    }

        TiXmlElement* element;

	    for( element = root->FirstChildElement();
		    element;
		    element = element->NextSiblingElement() )
	    {
            if (strcmp(element->Value(), "property") == 0)
            {
                String strName = element->Attribute("name");
                String strValue = element->Attribute("value");

                if (strName != "" && strValue != "")
                {
                    m_Settings[strName] = strValue;
                }
            }   
	    }
        
        return true;
    }

	//-----------------------------------------------------------------------
    bool CXMLConfigFile::Save(const String& strFilename, ConfigOptionMap ConfigMap)
    {
		char str[128];
        TiXmlDocument doc(strFilename.c_str());
		
		// XML Declaration
        TiXmlDeclaration decl("1.0", "UTF-8", "Yes");
		
		// XML Comment: Keos version
		TiXmlComment ver;
		sprintf(str," Keos %s ", CRoot::Instance().GetVersion().c_str());
		ver.SetValue(str);

		// XML Comment: Last save: date and time
		TiXmlComment lastmodified;
        char sDate[24];
        time_t CurrentTime = time(NULL);
        strftime(sDate, sizeof(sDate), "%d/%m/%Y", localtime(&CurrentTime));
		char sTime[24];
		strftime(sTime, sizeof(sTime), "%H:%M:%S", localtime(&CurrentTime));
		sprintf(str," Last save: %s %s ", sDate, sTime);
		lastmodified.SetValue(str);

		// Root XML Element
        TiXmlElement root("properties");
          
		// Insert XML Elements: property
        for(
            ConfigOptionMap::iterator it = ConfigMap.begin();
            it != ConfigMap.end();
            ++it )
        {
            TiXmlElement node("property");
            node.SetAttribute("name", it->second.name.c_str());
            node.SetAttribute("value", it->second.currentValue.c_str());
            root.InsertEndChild(node);  
        }

		doc.InsertEndChild(decl);
		doc.InsertEndChild(ver);
		doc.InsertEndChild(lastmodified);
		doc.InsertEndChild(root);

		return doc.SaveFile();	
    }
    
    //-----------------------------------------------------------------------
    String CXMLConfigFile::GetSetting(const String& strKey) const
    {
        SettingsMap::const_iterator i = m_Settings.find(strKey);
        if (i == m_Settings.end())
        {
            return CStringUtil::BLANK;
        }
        else
        {
            return i->second;
        }     
    }   
} // namespace Keos
