
#include <config.hpp>

#if defined(BUILD_CLIENT)
#include "game/engine/engine.hpp"
#include "game/audio/audio.hpp"
#endif
#if defined(BUILD_SERVER)
#include "server/server.hpp"
#endif
#include "common/command_arguments_parser.hpp"
#include "common/logger.hpp"
#include "common/locale/translation_manager.hpp"

int main(int argc, char** argv) {
	polygun::utils::Logger::create(false, true);
	polygun::locale::TranslationManager::create("locale");

	polygun::utils::CommandArgumentsParser parser(argc, argv);
	parser.parse();
#if defined(BUILD_SERVER)
	if(parser.start_server()) {
		try {
			polygun::server::Server server;
			server.run();
		}
		catch(const std::string& msg) {
			LOG_ERROR("Server runtime failed: %s", msg.c_str());
		}
	}
	else {
#endif
#if defined(BUILD_CLIENT)
		polygun::engine::DirectJoinArguments* direct_join = nullptr;
#if defined(BUILD_SERVER)
		if(parser.host_server())
			direct_join = new polygun::engine::DirectJoinArguments;
#endif
		if(parser.connect_to())
			direct_join = new polygun::engine::DirectJoinArguments;
#if defined(BUILD_SERVER)
		if(parser.host_server()) {
			direct_join->m_ip = "127.0.0.1";
			direct_join->m_port = 1337;
			direct_join->m_nickname = parser.get_host_server_nickname();
			direct_join->m_host_server = true;
		}
		else
#endif
		if(parser.connect_to()) {
			direct_join->m_ip = parser.get_connect_ip();
			direct_join->m_port = parser.get_connect_port();
			direct_join->m_nickname = parser.get_connect_nickname();
			direct_join->m_host_server = false;
		}
		polygun::audio::init();
		polygun::engine::Engine engine;
		engine.init(direct_join);
		polygun::audio::cleanup();
		if(direct_join)
			delete direct_join;
#endif
#if defined(BUILD_SERVER)
	}
#endif
	polygun::locale::TranslationManager::cleanup();
	polygun::utils::Logger::cleanup();
	return 0;
}
