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

#include "common/logger.hpp"
#include "server/server.hpp"
#include "server/mod_manager.hpp"

using namespace polygun::server;

// Logging
void mod_api::log_info(asIScriptGeneric* args) {
	std::string* msg = (std::string*)args->GetArgAddress(0);
	const char* section;
	int line = g_current_modmanager->get_script_context()->GetLineNumber(0, nullptr, &section);
	std::string file = g_current_modmanager->get_current_module()->get_mod_path()+"/"+std::string(section);
	utils::Logger::get().info(file.c_str(), static_cast<size_t>(line), "%s", msg->c_str());
}

void mod_api::log_warning(asIScriptGeneric* args) {
	std::string* msg = (std::string*)args->GetArgAddress(0);
	const char* section;
	int line = g_current_modmanager->get_script_context()->GetLineNumber(0, nullptr, &section);
	std::string file = g_current_modmanager->get_current_module()->get_mod_path()+"/"+std::string(section);
	utils::Logger::get().warning(file.c_str(), static_cast<size_t>(line), "%s", msg->c_str());
}

void mod_api::log_error(asIScriptGeneric* args) {
	std::string* msg = (std::string*)args->GetArgAddress(0);
	const char* section;
	int line = g_current_modmanager->get_script_context()->GetLineNumber(0, nullptr, &section);
	std::string file = g_current_modmanager->get_current_module()->get_mod_path()+"/"+std::string(section);
	utils::Logger::get().error(file.c_str(), static_cast<size_t>(line), "%s", msg->c_str());
}

void mod_api::log_fatal(asIScriptGeneric* args) {
	std::string* msg = (std::string*)args->GetArgAddress(0);
	const char* section;
	int line = g_current_modmanager->get_script_context()->GetLineNumber(0, nullptr, &section);
	std::string file = g_current_modmanager->get_current_module()->get_mod_path()+"/"+std::string(section);
	utils::Logger::get().fatal(file.c_str(), static_cast<size_t>(line), "%s", msg->c_str());
}

void mod_api::log_verbose(asIScriptGeneric* args) {
	std::string* msg = (std::string*)args->GetArgAddress(0);
	const char* section;
	int line = g_current_modmanager->get_script_context()->GetLineNumber(0, nullptr, &section);
	std::string file = g_current_modmanager->get_current_module()->get_mod_path()+"/"+std::string(section);
	utils::Logger::get().verbose(file.c_str(), static_cast<size_t>(line), "%s", msg->c_str());
}

// Util classes
mod_api::RefCounted::RefCounted(asIScriptObject* script_obj) :
	m_ref_count(1),
	m_script_obj(script_obj),
	m_active(script_obj->GetWeakRefFlag())
{
	m_active->AddRef();
}

mod_api::RefCounted::~RefCounted() {
	m_active->Release();
}

void mod_api::RefCounted::reference() {
	m_ref_count++;
	if(!m_active->Get())
		m_script_obj->AddRef();
}

void mod_api::RefCounted::release() {
	if(!m_active->Get())
		m_script_obj->Release();
	if(--m_ref_count==0)
		delete this;
}

// Registering nodes
mod_api::Node::Node(asIScriptObject* script_obj) :
	RefCounted(script_obj)
{}

static inline std::string node_texture_filename(asILockableSharedBool* active, asIScriptObject* script_obj, const std::string& method_signature) {
	std::string result = "builtin/texture/empty";
	if(active->Get())
		return result;
	asIScriptEngine* engine = script_obj->GetEngine();
	asIScriptContext* context = engine->RequestContext();
	asIScriptFunction* method = script_obj->GetObjectType()->GetMethodByDecl(method_signature.c_str());
	if(!method) {
		engine->ReturnContext(context);
		return result;
	}
	context->Prepare(method);
	context->SetObject(script_obj);
	if(context->Execute()==asEXECUTION_FINISHED)
		result = *(std::string*)context->GetReturnObject();
	engine->ReturnContext(context);
	return result;
}

std::string mod_api::Node::get_texture_filename() {
	return node_texture_filename(m_active, m_script_obj, "string get_texture_filename()");
}

std::string mod_api::Node::get_display_icon() {
	return node_texture_filename(m_active, m_script_obj, "string get_display_icon()");
}

std::string mod_api::Node::get_top_texture_filename() {
	return node_texture_filename(m_active, m_script_obj, "string get_top_texture_filename()");
}

std::string mod_api::Node::get_bottom_texture_filename() {
	return node_texture_filename(m_active, m_script_obj, "string get_bottom_texture_filename()");
}

std::string mod_api::Node::get_left_texture_filename() {
	return node_texture_filename(m_active, m_script_obj, "string get_left_texture_filename()");
}

std::string mod_api::Node::get_right_texture_filename() {
	return node_texture_filename(m_active, m_script_obj, "string get_right_texture_filename()");
}

std::string mod_api::Node::get_front_texture_filename() {
	return node_texture_filename(m_active, m_script_obj, "string get_front_texture_filename()");
}

std::string mod_api::Node::get_back_texture_filename() {
	return node_texture_filename(m_active, m_script_obj, "string get_back_texture_filename()");
}

mod_api::Node* mod_api::Node::create() {
	asIScriptContext* context = asGetActiveContext();
	asIScriptFunction* func = context->GetFunction(0);
	if(!func->GetObjectType() || std::string(func->GetObjectType()->GetName()) != "Node") {
		context->SetException("Invalid attempt to manually instantiate Node");
		return nullptr;
	}
	asIScriptObject* script_obj = reinterpret_cast<asIScriptObject*>(context->GetThisPointer(0));
	return new Node(script_obj);
}

void mod_api::register_node(asIScriptGeneric* args) {
	std::string* string_id = (std::string*)args->GetArgAddress(0);
	Node* node = (Node*)args->GetArgAddress(1);

	// Prepare NodeDef
	world::NodeDef def;
	def.m_string_id = *string_id;
	def.m_texture_filename = node->get_texture_filename();
	def.m_display_icon = node->get_display_icon();
	if(def.m_display_icon=="builtin/texture/empty")
		def.m_display_icon = def.m_texture_filename;
	def.m_top_texture_filename = node->get_top_texture_filename();
	def.m_bottom_texture_filename = node->get_bottom_texture_filename();
	def.m_left_texture_filename = node->get_left_texture_filename();
	def.m_right_texture_filename = node->get_right_texture_filename();
	def.m_front_texture_filename = node->get_front_texture_filename();
	def.m_back_texture_filename = node->get_back_texture_filename();

	g_current_modmanager->get_server().register_node(def);

	LOG_VERBOSE("Registered node %s", def.m_string_id.c_str());
}
