/*
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.
*/

#ifndef POLYGUN_SERVER_MOD_MANAGER_HPP
#define POLYGUN_SERVER_MOD_MANAGER_HPP

#include "server/mod.hpp"

namespace polygun::server {
	class Server;
	class ModManager final {
	public:
		ModManager(Server& server);
		~ModManager();

		void enumerate_modules();
		void run_modules();
		bool load_mod_resource(const std::string& name, std::vector<uint8_t>& output);

		Server& get_server() { return m_server; }
		asIScriptEngine* get_script_engine() { return m_engine; }
		asIScriptContext* get_script_context() { return m_context; }
		void set_current_module(Mod* module) { m_current_module = module; }
		Mod* get_current_module() { return m_current_module; }
		uint16_t get_next_node_id() { return m_current_node_id++; }
		uint16_t get_current_node_id() const { return m_current_node_id; }

	private:
		Server& m_server;
		asIScriptEngine* m_engine;
		asIScriptContext* m_context;
		std::vector<Mod> m_modules;
		Mod* m_current_module;
		// FIXME: This is wrong approach with assigning numeric IDs to nodes because if user
		// uninstalls mod then IDs will be overriden with wrong numbers
		uint16_t m_current_node_id;

	private:
		bool get_mod_path_by_name(const std::string& name, std::string& output);
		// API
		void init_api();
		void register_api_function(const std::string& signature, const asSFuncPtr& ptr);
		void register_object_method(const std::string& class_name, const std::string& signature, const asSFuncPtr& ptr);
	};

	extern ModManager* g_current_modmanager;
}

#endif
