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

#include <cstring>
#include <iostream>
#include <csignal>
#include <algorithm>
#include <config.hpp>
#if defined(__unix__)
#include <sys/ioctl.h>
#endif

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

using namespace polygun::server;

static Server* g_current_server = nullptr;

Server::Server(std::atomic<bool>* running_atomic, std::optional<unsigned short> port_override) :
	m_config(),
	m_running(running_atomic?running_atomic:new std::atomic<bool>),
	m_running_atomic_created(!running_atomic),
	m_clients(),
	m_latest_client(),
	m_server_socket(new polygun::network::UDPSocket),
	m_command_thread(),
	m_mod_manager(*this)
{
	LOG_INFO("Starting server");
	m_server_socket->bind(port_override.value_or(m_config.m_port));
	if(m_running_atomic_created) {
		srand(time(nullptr));
		m_running->store(true);
		g_current_server = this;
		signal(SIGINT, signal_handler);
		signal(SIGTERM, signal_handler);
#if defined(__unix__)
		signal(SIGQUIT, signal_handler);
		signal(SIGSTOP, signal_handler);
#endif
		m_command_thread.reset(new std::thread(&Server::command_thread_func, this));
	}
	m_mod_manager.enumerate_modules();
}

Server::~Server() {
	LOG_INFO("Shutting down server");
	if(m_running_atomic_created) {
		LOG_VERBOSE("Waiting for command thread to finish");
		if(m_command_thread->joinable())
			m_command_thread->join();
		delete m_running;
	}
}

void Server::run() {
	m_mod_manager.run_modules();
	polygun::network::NetworkPacket packet;
	while(m_running->load()) {
		bool handled = false;
		polygun::network::NetworkEndpoint sender;
		memset((void*)&sender, 0, sizeof(sender));
		sender.sin_family = AF_INET;
		sender.sin_addr.s_addr = INADDR_ANY;
		for(size_t i = 0; i<m_clients.size(); i++) {
			m_clients[i]->get_connection().update();
			if(time(0)-m_clients[i]->get_last_activity()>=10) {
				handle_player_timeout(m_clients[i].get());
				m_clients.erase(m_clients.begin()+i);
				i--;
			}
		}
		if(!m_server_socket->recv(packet, &sender))
			continue;

		for(size_t i = 0; i<m_clients.size(); i++) {
			Client& client = *m_clients[i];
			if(memcmp(&sender, &client.get_connection().get_endpoint(), sizeof(polygun::network::NetworkEndpoint))==0) {
				if(client.get_join_completed() && packet.get_id()==polygun::network::NetworkPacketID::PACKET_HANDSHAKE) {
					LOG_WARNING("Player %s(%d) has resent handshake packet!!", client.get_nick().c_str(), client.get_uuid());
					handled = true;
				}
				else if((packet.get_flags() & polygun::network::NetworkPacketFlag::FLAG_RELIABLE) || packet.get_id()==polygun::network::NetworkPacketID::PACKET_ACK)
					client.get_connection().push_packet(packet);
				else if(!handle_packet(packet, &client)) {
					handle_player_disconnected(&client);
					m_clients.erase(m_clients.begin()+i);
					i--;
				}
				handled = true;
			}

			if(client.get_connection().recv_packet(packet)) {
				if(!handle_packet(packet, &client)) {
					m_clients.erase(m_clients.begin()+i);
					i--;
				}
			}
		}

		if(!handled && packet.get_id()==polygun::network::NetworkPacketID::PACKET_HANDSHAKE) {
			std::unique_ptr<polygun::network::NetworkManager> network_manager = std::make_unique<polygun::network::NetworkManager>(m_server_socket, sender);
			network_manager->increment_incoming_packet_counter();
			m_latest_client.reset(new Client(std::move(network_manager)));
			if(handle_new_player(packet)) {
				LOG_INFO("Player %s joined the game (uuid: %d)", m_latest_client->get_nick().c_str(), m_latest_client->get_uuid());
				m_clients.push_back(std::move(m_latest_client));
			}
		}
	}
}

void Server::register_node(const world::NodeDef& def) {
	m_node_defs[def.m_string_id] = def;
	m_node_defs[def.m_string_id].m_id = m_mod_manager.get_next_node_id();
}

void Server::command_thread_func() {
	std::string line;
	bool has_input_data = false;
	bool show_input_prompt = true;
	CommandParser parser(*this);
	while(m_running->load()) {
		if(show_input_prompt) {
			std::cout<<"> ";
			std::cout.flush();
			show_input_prompt = false;
		}
#if defined(__unix__)
		int byte_count = 0;
		ioctl(0, FIONREAD, &byte_count);
		if(byte_count>0) {
			has_input_data = true;
			getline(std::cin, line);
		}
#elif defined(_WIN32)
		// FIXME: Support Unicode characters there
		// Note: this code is very hacky but it works
		HANDLE stdin_handle = GetStdHandle(STD_INPUT_HANDLE);
		INPUT_RECORD records[4];
		DWORD record_count;
		ReadConsoleInput(stdin_handle, records, sizeof(records)/sizeof(INPUT_RECORD), &record_count);
		for(DWORD i = 0; i<record_count; i++) {
			if(records[i].EventType==KEY_EVENT && records[i].Event.KeyEvent.bKeyDown) {
				CHAR ch = records[i].Event.KeyEvent.uChar.AsciiChar;
				if(isprint(ch)) {
					line+=ch;
					std::cout<<ch;
					std::cout.flush();
				}
				else if(ch==8 && !line.empty()) {
					line.back()=' ';
					std::cout<<"\r> "<<line;
					line.pop_back();
					std::cout<<"\r> "<<line;
				}
				else if(ch==13) {
					std::cout<<std::endl;
					has_input_data = true;
					break;
				}
			}
		}
#endif
		if(has_input_data) {
			parser.parse(line);
			has_input_data = false;
			show_input_prompt = true;
#if defined(_WIN32)
			line.clear();
#endif
		}
	}
}

bool Server::handle_packet(polygun::network::NetworkPacket& packet, Client* client) {
	switch(packet.get_id()) {
	case polygun::network::NetworkPacketID::PACKET_HANDSHAKE:
		return handle_new_player(packet);
	case polygun::network::NetworkPacketID::PACKET_NODE_DEFINITION:
		handle_node_definition(packet, client);
		return true;
	case polygun::network::NetworkPacketID::PACKET_RESOURCE:
		handle_resource_request(packet, client);
		return true;
	case polygun::network::NetworkPacketID::PACKET_EXIT:
		handle_player_disconnected(client);
		break;
	case polygun::network::NetworkPacketID::PACKET_ACTIVITY:
		handle_player_activity(client);
		return true;
	}
	return false;
}

bool Server::handle_new_player(polygun::network::NetworkPacket& packet) {
	std::string nick;
	packet.read(nick);
	m_latest_client->set_nick(nick);
	// Generate UUID
	bool unique = true;
	uint32_t uuid;
	// FIXME: there is possible hang here
	do{
		uuid = rand();
		for(const std::unique_ptr<Client>& client : m_clients)
			unique = uuid != client->get_uuid();
	}
	while(!unique);

	m_latest_client->get_connection().send_ack(packet.get_num());
	polygun::network::NetworkPacket out_packet = m_latest_client->get_connection().create_packet(polygun::network::NetworkPacketFlag::FLAG_RELIABLE, polygun::network::NetworkPacketID::PACKET_HANDSHAKE);
	out_packet.write(uuid);
	out_packet.write(m_mod_manager.get_current_node_id());
	m_latest_client->get_connection().send_packet(out_packet);
	m_latest_client->set_uuid(uuid);
	m_latest_client->set_join_completed_flag();

	return true;
}

void Server::handle_node_definition(polygun::network::NetworkPacket& packet, Client* client) {
	uint16_t node_id;
	if(!packet.read(node_id)) {
		LOG_ERROR("Player %s(%d) sent invalid node definition request", client->get_nick().c_str(), client->get_uuid());
		return;
	}

	network::NetworkPacket out_packet = client->get_connection().create_packet(network::NetworkPacketFlag::FLAG_RELIABLE, network::NetworkPacketID::PACKET_NODE_DEFINITION);

	std::map<std::string, world::NodeDef>::iterator it = std::find_if(m_node_defs.begin(), m_node_defs.end(), [node_id](const std::pair<std::string, world::NodeDef>& element) {
		return element.second.m_id==node_id;
	});
	out_packet.write(node_id);
	if(it==m_node_defs.end()) {
		world::NodeDef unknown_node;
		unknown_node.m_string_id = "builtin:unknown";
		out_packet.write(&unknown_node);
	}
	else
		out_packet.write(&it->second);

	client->get_connection().send_packet(out_packet);
}

void Server::handle_resource_request(polygun::network::NetworkPacket& packet, Client* client) {
	std::string resource_id;
	if(!packet.read(resource_id)) {
		LOG_ERROR("Player %s(%d) sent invalid resource request", client->get_nick().c_str(), client->get_uuid());
		return;
	}

	std::vector<uint8_t> resource_data;
	if(!m_mod_manager.load_mod_resource(resource_id, resource_data)) {
		send_empty_resource(client, resource_id);
		return;
	}

	// FIXME: Allow resources bigger than maximum UDP packet size
	// Actually this is not the maximum packet size, it's around 5 KiB less
	if(resource_data.size()>61440) { // 60 KiB
		LOG_VERBOSE("(FIXME) Requested resource is too large to be sent (%zu B), sending empty resource instead", resource_data.size());
		send_empty_resource(client, resource_id);
		return;
	}

	network::NetworkPacket p = client->get_connection().create_packet(network::NetworkPacketFlag::FLAG_RELIABLE, network::NetworkPacketID::PACKET_RESOURCE);
	p.write(resource_id);
	p.write(resource_data);
	client->get_connection().send_packet(p);
}

void Server::handle_player_disconnected(const Client* client) {
	LOG_INFO("Player %s(%d) left the game", client->get_nick().c_str(), client->get_uuid());

	for(std::unique_ptr<Client>& c : m_clients) {
		if(c->get_uuid()==client->get_uuid())
			continue;
		polygun::network::NetworkPacket packet = c->get_connection().create_packet(polygun::network::NetworkPacketFlag::FLAG_RELIABLE, polygun::network::NetworkPacketID::PACKET_EXIT);
		packet.write(client->get_uuid()); // client UUID
		packet.write((uint8_t)0); // reason ID
		c->get_connection().send_packet(packet);
	}
}

void Server::handle_player_timeout(const Client* client) {
	LOG_INFO("Player %s(%d) has left the game: timeout", client->get_nick().c_str(), client->get_uuid());

	for(std::unique_ptr<Client>& c : m_clients) {
		if(c->get_uuid()==client->get_uuid())
			continue;
		polygun::network::NetworkPacket packet = c->get_connection().create_packet(polygun::network::NetworkPacketFlag::FLAG_RELIABLE, polygun::network::NetworkPacketID::PACKET_EXIT);
		packet.write(client->get_uuid()); // client UUID
		packet.write((uint8_t)1); // reason ID
		c->get_connection().send_packet(packet);
	}
}

void Server::handle_player_activity(Client* client) {
	client->update_activity();
}

void Server::send_empty_resource(Client* client, const std::string& resource_id) {
	network::NetworkPacket packet = client->get_connection().create_packet(network::NetworkPacketFlag::FLAG_RELIABLE, network::NetworkPacketID::PACKET_RESOURCE);
	packet.write(resource_id);
	packet.write(static_cast<uint16_t>(0));
	client->get_connection().send_packet(packet);
}

#if !defined(HAVE_STRSIGNAL)
static const char* strsignal(int sig) {
	switch(sig){
	case SIGINT:
		return "Interrupt";
	case SIGTERM:
		return "Terminated";
	}
	return nullptr;
}
#endif
void Server::signal_handler(int sig) {
	if(!g_current_server)
		return;

	const char* signal_name = strsignal(sig);
	if(!signal_name)
		signal_name = "Unknown";

	LOG_INFO("Received %s signal", signal_name);
	g_current_server->m_running->store(false);
}
