/*
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 "common/locale/dictionary.hpp"

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

using namespace polygun::locale;

Dictionary::Dictionary() :
	m_data()
{}

void Dictionary::load_from_file(const std::string& path) {
	xml::XMLNode* root_node;
	if(!xml::parse_file(path, root_node)) {
		LOG_ERROR("Failed to load translation '%s'", path.c_str());
		delete root_node;
		return;
	}

	if(root_node->get_name()!="locale") {
		LOG_ERROR("Failed to load translation '%s': not a locale file", path.c_str());
		delete root_node;
		return;
	}

	m_data.clear();
	for(xml::XMLNode* node = root_node->next_node(); node; node = root_node->next_node()) {
		if(node->get_name()!="tr") {
			LOG_ERROR("Invalid tag '%s' in locale file '%s'", node->get_name().c_str(), path.c_str());
			delete root_node;
			return;
		}
		xml::XMLNode* msgid = node->next_node("msgid");
		xml::XMLNode* msgstr = node->next_node("msgstr");
		if(!msgid || !msgstr) {
			LOG_ERROR("Invalid locale entry in locale file '%s'", path.c_str());
			delete root_node;
			return;
		}
		m_data[msgid->get_text()] = msgstr->get_text();
	}

	delete root_node;
}

const std::string& Dictionary::get(const std::string& msgid) {
	if(!m_data.count(msgid))
		return msgid;
	return m_data[msgid];
}
