/*
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_SERVER_HPP
#define POLYGUN_SERVER_SERVER_HPP

#include <atomic>
#include <thread>
#include <map>
#include <optional>

#include "server/client.hpp"
#include "server/mod_manager.hpp"
#include "server/server_config.hpp"
#include "common/world/node_def.hpp"

namespace polygun::server {
	class Server final {
		friend class CommandParser;
	public:
		Server(std::atomic<bool>* running_atomic = nullptr, std::optional<unsigned short> port_override = std::nullopt);
		~Server();

		void run();

		void register_node(const world::NodeDef& def);

		const ServerConfig& get_config() const { return m_config; }

	private:
		ServerConfig m_config;
		std::atomic<bool>* m_running;
		bool m_running_atomic_created;
		std::vector<std::unique_ptr<Client>> m_clients;
		std::unique_ptr<Client> m_latest_client;
		std::shared_ptr<polygun::network::UDPSocket> m_server_socket;
		std::unique_ptr<std::thread> m_command_thread;
		ModManager m_mod_manager;
		std::map<std::string, world::NodeDef> m_node_defs;

	private:
		void command_thread_func();

		bool handle_packet(polygun::network::NetworkPacket& packet, Client* client = nullptr);
		bool handle_new_player(polygun::network::NetworkPacket& packet);
		void handle_node_definition(polygun::network::NetworkPacket& packet, Client* client);
		void handle_resource_request(polygun::network::NetworkPacket& packet, Client* client);
		void handle_player_disconnected(const Client* client);
		void handle_player_timeout(const Client* client);
		void handle_player_activity(Client* client);
		void handle_invalid_packet(const Client& client, const polygun::network::NetworkPacket& packet);
		void send_empty_resource(Client* client, const std::string& resource_id);

		static void signal_handler(int sig);
	};
}

#endif // POLYGUN_SERVER_SERVER_HPP
