/*
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/xml/parser.hpp"

#include <fstream>
#include <sstream>

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

bool polygun::xml::parse(std::istream& stream, XMLNode*& output) {
	std::vector<XMLToken> tokens;
	if(!tokenize(stream, tokens))
		return false;

	size_t offset = 0;
	std::vector<XMLNode*> node_stack;
	XMLNode* last_node;
	while(offset<tokens.size()) {
		if(tokens[offset].m_type==XMLToken::XML_TOKEN_TYPE_LBRACKET && offset+1<tokens.size()) {
			if(tokens[++offset].m_type==XMLToken::XML_TOKEN_TYPE_IDENTIFIER) {
				XMLNode* temp_node = new XMLNode;
				if(!node_stack.empty())
					node_stack.back()->add_node(temp_node);
				node_stack.push_back(temp_node);
				node_stack.back()->set_name(tokens[offset].m_data);
				while(++offset<tokens.size() && tokens[offset].m_type!=XMLToken::XML_TOKEN_TYPE_RBRACKET) {
					const XMLToken& key = tokens[offset++];
					if(offset>=tokens.size()) {
						LOG_ERROR("Unexpected end of input after %s token at %zu:%zu", key.get_string_name().c_str(), key.m_line, key.m_column);
						return false;
					}
					if(key.m_type!=XMLToken::XML_TOKEN_TYPE_IDENTIFIER){
						LOG_ERROR("Expected IDENTIFIER at %zu:%zu", key.m_line, key.m_column);
						return false;
					}
					const XMLToken& equals = tokens[offset++];
					if(offset>=tokens.size()) {
						LOG_ERROR("Unexpected end of input after %s token at %zu:%zu", equals.get_string_name().c_str(), equals.m_line, equals.m_column);
						return false;
					}
					if(equals.m_type!=XMLToken::XML_TOKEN_TYPE_EQUALS){
						LOG_ERROR("Expected '=' at %zu:%zu", equals.m_line, equals.m_column);
						return false;
					}
					const XMLToken& str = tokens[offset];
					if(offset>=tokens.size()) {
						LOG_ERROR("Unexpected end of input after %s token at %zu:%zu", str.get_string_name().c_str(), str.m_line, str.m_column);
						return false;
					}
					if(str.m_type!=XMLToken::XML_TOKEN_TYPE_STRING){
						LOG_ERROR("Expected STRING at %zu:%zu", str.m_line, str.m_column);
						return false;
					}
					node_stack.back()->add_attribute(key.m_data, str.m_data);
				}
				offset++;
			}
			else if(tokens[offset].m_type==XMLToken::XML_TOKEN_TYPE_SLASH) {
				if(++offset>=tokens.size()) {
					LOG_ERROR("Unexpected end of input after %s token at %zu:%zu", tokens[offset-1].get_string_name().c_str(), tokens[offset-1].m_line, tokens[offset-1].m_column);
					return false;
				}
				XMLToken& identifier = tokens[offset];
				if(identifier.m_type!=XMLToken::XML_TOKEN_TYPE_IDENTIFIER) {
					LOG_ERROR("Expected IDENTIFIER at %zu:%zu", identifier.m_line, identifier.m_column);
					return false;
				}
				if(++offset>=tokens.size()) {
					LOG_ERROR("Unexpected end of input after %s token at %zu:%zu", tokens[offset-1].get_string_name().c_str(), tokens[offset-1].m_line, tokens[offset-1].m_column);
					return false;
				}
				XMLToken& rbracket = tokens[offset];
				if(rbracket.m_type!=XMLToken::XML_TOKEN_TYPE_RBRACKET) {
					LOG_ERROR("Expected RBRACKET at %zu:%zu", rbracket.m_line, rbracket.m_column);
					return false;
				}
				if(identifier.m_data!=node_stack.back()->get_name()) {
					LOG_ERROR("Mismatched tag close at %zu:%zu", identifier.m_line, identifier.m_column);
					return false;
				}
				last_node = node_stack.back();
				node_stack.pop_back();
				offset++;
			}
		}
		else if(tokens[offset].m_type==XMLToken::XML_TOKEN_TYPE_TEXT) {
			if(node_stack.size()>0)
				node_stack.back()->set_text(node_stack.back()->get_text()+tokens[offset].m_data);
			offset++;
		}
		else {
			LOG_ERROR("Unexpected token %s at %zu:%zu", tokens[offset].get_string_name().c_str(), tokens[offset].m_line, tokens[offset].m_column);
			return false;
		}
	}
	if(!node_stack.empty()) {
		LOG_ERROR("Unclosed tag '%s'", node_stack.back()->get_name().c_str());
		return false;
	}
	if(last_node) {
		output = last_node;
	}
	return true;
}

bool polygun::xml::parse_string(const std::string& str, polygun::xml::XMLNode*& output) {
	std::stringstream ss;
	ss<<str;
	return parse(ss, output);
}

bool polygun::xml::parse_file(const std::string& path, polygun::xml::XMLNode*& output) {
	std::ifstream file(path);
	if(!file.good()) {
		LOG_ERROR("While parsing XML file '%s': failed to open file", path.c_str());
		return false;
	}
	bool result = parse(file, output);
	file.close();
	return result;
}
