/*
PolyGun

Copyright (c) 2023 mrkubax10 <mrkubax10@onet.pl>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

#include "server/server_config.hpp"

#include <fstream>

#include "common/xml/parser.hpp"
#include "common/xml/reader.hpp"
#include "common/xml/xml_node.hpp"
#include "common/fs.hpp"
#include "common/logger.hpp"

using namespace polygun::server;

ServerConfig::ServerConfig() :
	m_user_dir(utils::get_user_dir()),
	m_port(1337),
	m_module_search_path(),
	m_config_generated(false)
{
	xml::XMLNode* root = nullptr;
	if(xml::parse_file(m_user_dir+"/server_config.xml", root) && root->get_name()=="server_config") {
		xml::XMLReader reader(root);
		unsigned temp;
		reader.get("port", temp);
		m_port = static_cast<unsigned short>(temp);
		xml::XMLNode* search_path = root->next_node("module_search_path");
		if(search_path) {
			for(xml::XMLNode* node = search_path->next_node(); node; node = search_path->next_node()) {
				if(node->get_name()!="path" || node->get_text().empty()) {
					LOG_WARNING("Invalid module search path entry (%s)", node->get_name().c_str());
					continue;
				}
				m_module_search_path.push_back(node->get_text());
			}
		}
	}
	else
		m_config_generated = true;
	if(m_module_search_path.empty()) {
		m_module_search_path.push_back("mods");
		m_config_generated = true;
	}
	if(root)
		delete root;
}

ServerConfig::~ServerConfig() {
	if(!m_config_generated)
		return;
	const std::string config_path = m_user_dir+"/server_config.xml";
	std::ofstream file(config_path);
	if(!file.good()) {
		LOG_ERROR("Failed to write server config file '%s'", config_path.c_str());
		return;
	}
	file<<"<server_config>"<<std::endl;
	file<<"\t<port>"<<m_port<<"</port>"<<std::endl;
	file<<"\t<module_search_path>"<<std::endl;
	for(const std::string& path : m_module_search_path)
		file<<"\t\t<path>"<<path<<"</path>"<<std::endl;
	file<<"\t</module_search_path>"<<std::endl;
	file<<"</server_config>"<<std::endl;
	file.close();
}
