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

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

using namespace polygun::server;

Mod::Mod(ModManager& mod_manager, const std::string& name, const std::string& mod_path):
	m_mod_manager(mod_manager),
	m_name(name),
	m_mod_path(mod_path),
	m_display_name(),
	m_description(),
	m_scripts(),
	m_module(mod_manager.get_script_engine()->GetModule(nullptr, asGM_ALWAYS_CREATE)),
	m_meta_loaded(false)
{
	load_meta();
}

void Mod::execute() {
	if(!m_meta_loaded)
		return;

	int error;
	for(const std::string& script : m_scripts) {
		FILE* file = fopen(std::string(m_mod_path+"/"+script).c_str(), "r");
		if(!file) {
			LOG_WARNING("Failed to open script '%s/%s'", m_mod_path.c_str(), script.c_str());
			continue;
		}

		fseek(file, 0, SEEK_END);
		long file_size = ftell(file);
		rewind(file);

		char* script_source = new char[file_size+1];
		fread(script_source, file_size, 1, file);
		script_source[file_size] = 0;

		fclose(file);

		if((error=m_module->AddScriptSection(script.c_str(), script_source, file_size))<0) {
			LOG_ERROR("Failed to load mod '%s': failed to add script '%s' section (error code: %d)", m_mod_path.c_str(), script.c_str(), error);
			return;
		}

		delete[] script_source;
	}

	load_interface();

	m_mod_manager.set_current_module(this);
	if((error=m_module->Build())<0) {
		LOG_ERROR("Failed to load mod '%s': failed to build script sections (error code: %d)", m_mod_path.c_str(), error);
		return;
	}

	asIScriptFunction* entry = m_module->GetFunctionByDecl("void main()");
	if(!entry) {
		LOG_ERROR("Failed to load mod '%s': entrypoint 'main' doesn't exist", m_mod_path.c_str());
		return;
	}
	asIScriptContext* context = m_mod_manager.get_script_context();
	if((error=context->Prepare(entry))<0) {
		LOG_ERROR("Failed to load mod '%s': failed to prepare context (error code: %d)", m_mod_path.c_str(), error);
		return;
	}
	error=context->Execute();
	if(error==asEXECUTION_EXCEPTION) {
		asIScriptFunction* exception = context->GetExceptionFunction();
		LOG_ERROR("Mod '%s' exited with exception in %s:%d with message '%s'", m_mod_path.c_str(), exception->GetDeclaration(), context->GetExceptionLineNumber(), context->GetExceptionString());		
	}
	else if(error==asEXECUTION_ABORTED)
		LOG_ERROR("Mod '%s' aborted", m_mod_path.c_str());
}

void Mod::load_meta() {
	xml::XMLNode* root_node;
	if(!xml::parse_file(m_mod_path+"/mod.xml", root_node)) {
		LOG_ERROR("Failed to load mod '%s': error while parsing mod.xml", m_mod_path.c_str());
		return;
	}

	if(root_node->get_name()!="mod") {
		LOG_ERROR("Failed to load mod '%s': mod.xml is invalid", m_mod_path.c_str());
		delete root_node;
		return;
	}

	xml::XMLNode* name = root_node->next_node("name");
	if(name)
		m_display_name = name->get_text();
	else
		m_display_name = m_mod_path;

	xml::XMLNode* description = root_node->next_node("description");
	if(description)
		m_description = description->get_text();

	xml::XMLNode* scripts = root_node->next_node("scripts");
	if(scripts) {
		for(xml::XMLNode* script = scripts->next_node(); script; script = scripts->next_node()) {
			if(script->get_name()!="script") {
				LOG_ERROR("Failed to load mod '%s': invalid script tag", m_mod_path.c_str());
				delete root_node;
				return;
			}
			if(!script->get_text().empty())
				m_scripts.push_back(script->get_text());
		}
	}
	else {
		LOG_ERROR("Failed to load mod '%s': mod.xml doesn't contain scripts tag", m_mod_path.c_str());
		delete root_node;
		return;
	}
	
	delete root_node;
	m_meta_loaded = true;
}

void Mod::load_interface() {
	const std::string interface_path = "mods/interface.as";
	int error;
	FILE* interface_file = fopen(interface_path.c_str(), "r");
	if(!interface_file)
		LOG_FATAL("Failed to open '%s'", interface_path.c_str());
	fseek(interface_file, 0, SEEK_END);
	long interface_file_size = ftell(interface_file);
	rewind(interface_file);
	char* interface_source = new char[interface_file_size+1];
	fread(interface_source, interface_file_size, 1, interface_file);
	interface_source[interface_file_size] = 0;
	fclose(interface_file);
	if((error=m_module->AddScriptSection(interface_path.c_str(), interface_source, interface_file_size))<0) {
		delete[] interface_source;
		LOG_FATAL("Failed to load '%s': failed to add script section (error code: %d)", interface_path.c_str(), error);
	}
	delete[] interface_source;
}
