/*
PolyGun

Copyright (c) 2023 mrkubax10 <mrkubax10@onet.pl>
              2023 kacperks

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 "game/screens/game_session_screen.hpp"

#include "common/network/network_manager.hpp"
#include "common/logger.hpp"
#include "common/locale/util.hpp"
#include "game/engine/engine.hpp"
#include "game/renderer/shader.hpp"
#include "game/renderer/mesh.hpp"
#include "game/renderer/texture.hpp"
#include "game/renderer/gui_renderer.hpp"
#include "game/window/window.hpp"
#if defined(BUILD_SERVER)
#include "server/server.hpp"
#endif

using namespace polygun::screens;

static uint16_t id_d;

GameSessionScreen::GameSessionScreen(const std::string& ip, unsigned short port, const std::string& player_nick, bool start_server) :
	m_greedy(),
	m_ip(ip),
	m_port(port),
	m_player_nick(player_nick),
#if defined(BUILD_SERVER)
	m_start_server(start_server),
	m_server_running(),
#endif
	m_chunk_shader(nullptr),
	m_node_mesh(nullptr),
	m_chnk(),
	m_camera(),
	m_resource_manager(),
	m_content_registry(),
	m_texture_atlas(),
	//m_is_esc_pressed(false),
	m_was_camera_locked(false),
	m_connection_thread(),
	m_network_mutex(),
#if defined(BUILD_SERVER)
	m_local_server_thread(),
#endif
	m_game_state(GameState::GAME_STATE_JOINING),
	m_player_uuid(0)
{}

void GameSessionScreen::begin() {
#if defined(BUILD_SERVER)
	if(m_start_server) {
		m_server_running = true;
		m_local_server_thread.reset(new std::thread(&GameSessionScreen::local_server_thread_func, this));
	}
#endif

	m_chunk_shader = m_engine->get_master_renderer()->create_shader();
	m_chunk_shader->load_from_file("chunk");

	m_node_mesh = m_engine->get_master_renderer()->create_mesh();
	update_mesh();
	id_d = 0;

	m_resource_manager.reset(new engine::ResourceManager(m_engine->get_master_renderer(), m_network_mutex));
	m_content_registry.reset(new engine::ContentRegistry(m_network_mutex));
	m_texture_atlas.reset(new engine::TextureAtlas(m_engine->get_master_renderer(), *m_content_registry, *m_resource_manager));

	m_engine->get_mesh_renderer()->set_shader(m_chunk_shader);
	m_engine->get_mesh_renderer()->set_camera(&m_camera);

	m_connection_thread.reset(new std::thread(&GameSessionScreen::connection_thread_func, this));
}

void GameSessionScreen::render() {
	//m_engine->get_master_renderer().clear_screen(clearcolor[0], clearcolor[1], clearcolor[2]);
	m_engine->get_master_renderer()->clear_screen(0, 0, 0);

	switch(m_game_state) {
	case GameState::GAME_STATE_JOINING:
	case GameState::GAME_STATE_LOADING:
	case GameState::GAME_STATE_FAILED:
	case GameState::GAME_STATE_TIMED_OUT:
	case GameState::GAME_STATE_FINISHED:
			break;
	case GameState::GAME_STATE_RUNNING:{
		renderer::MeshRenderer* mesh_renderer = m_engine->get_mesh_renderer();
		mesh_renderer->set_3d_rendering_mode(true);
		mesh_renderer->render(m_node_mesh, glm::vec4(0.5f, 0.5f, 0.5f, 1.0f));

		world::NodeDef selected_node = m_content_registry->get_node_def(id_d);
		m_engine->get_gui_renderer()->render_texture(glm::vec2(1,1), m_resource_manager->get_texture(selected_node.m_display_icon), glm::vec2(10,10), 0.0f, glm::vec4(1.0f,1.0f,1.0f,1.0f));
		break;
	}
	}
}

void GameSessionScreen::update(double delta) {
	// input
	// -----
	switch(m_game_state) {
	case GameState::GAME_STATE_JOINING:
		break;
	case GameState::GAME_STATE_LOADING:
		if(m_content_registry->are_all_node_defs_available()) {
			m_game_state = GameState::GAME_STATE_RUNNING;
			m_texture_atlas->construct();
		}
		break;
	case GameState::GAME_STATE_FAILED:
	case GameState::GAME_STATE_TIMED_OUT:
		m_engine->get_window()->grab_mouse(false);
		break;
	case GameState::GAME_STATE_FINISHED:
		break;
	case GameState::GAME_STATE_RUNNING:{
		if(m_engine->get_window()->is_keyboard_key_pressed(window::KeyCode::KEY_W))
			m_camera.process_movement(polygun::engine::FORWARD, delta);
		if(m_engine->get_window()->is_keyboard_key_pressed(window::KeyCode::KEY_S))
			m_camera.process_movement(polygun::engine::BACKWARD, delta);
		if(m_engine->get_window()->is_keyboard_key_pressed(window::KeyCode::KEY_A))
			m_camera.process_movement(polygun::engine::LEFT, delta);
		if(m_engine->get_window()->is_keyboard_key_pressed(window::KeyCode::KEY_D))
			m_camera.process_movement(polygun::engine::RIGHT, delta);
		if(m_engine->get_window()->is_keyboard_key_pressed(window::KeyCode::KEY_SPACE))
			m_camera.process_movement(polygun::engine::UP, delta);
		if(m_engine->get_window()->is_keyboard_key_pressed(window::KeyCode::KEY_LEFT_CONTROL))
			m_camera.process_movement(polygun::engine::DOWN, delta);

		m_engine->get_mesh_renderer()->set_camera(&m_camera);

		m_texture_atlas->update();
		break;
	}
	}
}

void GameSessionScreen::event(const window::Event& ev) {
	switch(m_game_state) {
	case GameState::GAME_STATE_JOINING:
	case GameState::GAME_STATE_LOADING:
	case GameState::GAME_STATE_FAILED:
	case GameState::GAME_STATE_TIMED_OUT:
	case GameState::GAME_STATE_FINISHED:
		break;
	case GameState::GAME_STATE_RUNNING:
		switch(ev.m_type) {
		case window::EventType::EVENT_TYPE_KEY_DOWN:
			if(ev.m_data.m_key_event.m_key==window::KeyCode::KEY_ESCAPE) {
				m_engine->get_window()->grab_mouse(!m_engine->get_window()->is_mouse_grabbed());
				m_was_camera_locked = true;
			}
			break;
		case window::EventType::EVENT_TYPE_MOUSE_BUTTON_DOWN:
			// "if cursor is captured and you can rotate the camera"
			if(m_engine->get_window()->is_mouse_grabbed()) {
				// right mouse button node place
				if (ev.m_data.m_mouse_event.m_button==window::MouseButton::MOUSE_BUTTON_RIGHT) {
					//m_chnk.add_node(id_d, glm::vec3(x_d, y_d, z_d));
				}
				// left mouse button node remove (place air)
				else if (ev.m_data.m_mouse_event.m_button==window::MouseButton::MOUSE_BUTTON_RIGHT) {
					//m_chnk.add_node(0, glm::vec3(x_d, y_d, z_d));
				}

				if(m_was_camera_locked) {
					m_camera.update(true);
					m_was_camera_locked = false;
				}
				else
					m_camera.update(false);
			}
			break;
		case window::EventType::EVENT_TYPE_MOUSE_WHEEL:
			// limit from 0 to size of polygun::world::nodes array change to sizeof and use id_d as a current node id
			if(ev.m_data.m_mouse_event.m_wheel_offset > 0) {
				if(id_d < m_content_registry->get_registered_node_count()-1) {
					id_d++;
				}
			} else {
				if(id_d > 0) {
					id_d--;
				}
			}
		default:
			break;
		}
		break;
	}
}

void GameSessionScreen::finish() {
	delete m_chunk_shader;
	delete m_node_mesh;

	m_game_state = GameState::GAME_STATE_FINISHED;
	if(m_connection_thread.get() && m_connection_thread->joinable()) {
		LOG_VERBOSE("Waiting for connection thread to finish");
		m_connection_thread->join();
	}

#if defined(BUILD_SERVER)
	if(m_start_server) {
		m_server_running = false;
		if(m_local_server_thread->joinable())
			m_local_server_thread->join();
	}
#endif

	m_resource_manager.reset();
	m_content_registry.reset();
	m_texture_atlas.reset();
}

void GameSessionScreen::connection_thread_func() {
	polygun::network::NetworkManager network_manager(m_ip, m_port);
	m_resource_manager->set_network_manager(&network_manager);
	m_content_registry->set_network_manager(&network_manager);
	polygun::network::NetworkPacket handshake = network_manager.create_packet(polygun::network::NetworkPacketFlag::FLAG_RELIABLE, polygun::network::NetworkPacketID::PACKET_HANDSHAKE);
	polygun::network::NetworkPacket packet;
	handshake.write(m_player_nick);
	network_manager.send_packet(handshake);
	unsigned short join_tries = 0;
	while(m_game_state!=GameState::GAME_STATE_FINISHED && m_game_state!=GameState::GAME_STATE_FAILED) {
		m_network_mutex.lock();
		network_manager.update();
		m_network_mutex.unlock();
		if(network_manager.get_socket().recv(packet)) {
			m_network_mutex.lock();
			if((packet.get_flags() & polygun::network::NetworkPacketFlag::FLAG_RELIABLE) || packet.get_id()==polygun::network::NetworkPacketID::PACKET_ACK)
				network_manager.push_packet(packet);
			if(network_manager.recv_packet(packet)) {
				switch(packet.get_id()) {
				case network::NetworkPacketID::PACKET_HANDSHAKE:
					if(m_game_state==GameState::GAME_STATE_JOINING) {
						m_game_state = GameState::GAME_STATE_LOADING;
						packet.read(m_player_uuid);
						LOG_INFO("Your player UUID: %d", m_player_uuid);
						uint16_t registered_node_count;
						packet.read(registered_node_count);
						LOG_INFO("%d registered nodes on this server", registered_node_count);
						m_content_registry->set_registered_node_count(registered_node_count);
						m_network_mutex.unlock();
						for(uint16_t i = 1; i<registered_node_count; i++)
							m_content_registry->request_node_def(i);
						m_network_mutex.lock();
					}
					else
						LOG_WARNING("Received another handshake packet from server!!");
					break;
				case network::NetworkPacketID::PACKET_NODE_DEFINITION:
					m_content_registry->on_packet(packet);
					break;
				case network::NetworkPacketID::PACKET_RESOURCE:
				case network::NetworkPacketID::PACKET_RESOURCE_CHECKSUM:
					m_resource_manager->on_packet(packet);
					break;
				}
			}
			m_network_mutex.unlock();
		}
		if(m_game_state==GameState::GAME_STATE_JOINING) {
			join_tries++;
			if(join_tries>5) {
				LOG_ERROR("Failed to connect to polygun://%s:%d (timed out)", m_ip.c_str(), m_port);
				m_game_state = GameState::GAME_STATE_FAILED;
				return;
			}
		}
		m_network_mutex.lock();
		packet = network_manager.create_packet(polygun::network::NetworkPacketFlag::FLAG_NONE, polygun::network::NetworkPacketID::PACKET_ACTIVITY);
		network_manager.send_packet(packet);
		m_network_mutex.unlock();
	}
	m_network_mutex.lock();
	packet = network_manager.create_packet(polygun::network::NetworkPacketFlag::FLAG_RELIABLE, polygun::network::NetworkPacketID::PACKET_EXIT);
	network_manager.send_packet(packet);
	m_network_mutex.unlock();
	while(network_manager.has_outgoing_packets()) {
		m_network_mutex.lock();
		if(network_manager.get_socket().recv(packet) && packet.get_id()==polygun::network::NetworkPacketID::PACKET_ACK)
			network_manager.push_packet(packet);
		network_manager.update();
		m_network_mutex.unlock();
	}
}

#if defined(BUILD_SERVER)
void GameSessionScreen::local_server_thread_func() {
	server::Server server(&m_server_running, std::optional(1337));
	server.run();
}
#endif

void GameSessionScreen::update_mesh(){
	std::vector<float> vertices;
	engine::vertices_indices mesh = m_greedy.generate_mesh(m_greedy.merge(m_chnk), m_chnk);
	for (size_t i = 0; i < mesh.vertices.size(); i++) {
		vertices.push_back(mesh.vertices[i].x);
		vertices.push_back(mesh.vertices[i].y);
		vertices.push_back(mesh.vertices[i].z);
	}
	m_node_mesh->load_from_memory(vertices, mesh.indices);
}
