////////////////////////////////////////////////////////////////////////////////
//    Scorched3D (c) 2000-2011, 2026
//
//    This file is part of Scorched3D.
//
//    Scorched3D is free software; you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation; either version 2 of the License, or
//    (at your option) any later version.
//
//    Scorched3D is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License along
//    with this program; if not, write to the Free Software Foundation, Inc.,
//    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
////////////////////////////////////////////////////////////////////////////////

#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#endif

#include <stdlib.h>
#include <weapons/AccessoryStore.hpp>
#include <weapons/EconomyStore.hpp>
#include <net/NetLoopBack.hpp>
#include <net/NetServerTCP3.hpp>
#include <lua/LUAScriptHook.hpp>
#include <common/Defines.hpp>
#include <common/Clock.hpp>
#include <common/ARGParser.hpp>
#include <common/Defines.hpp>
#include <common/Logger.hpp>
#include <common/OptionsScorched.hpp>
#include <common/OptionsTransient.hpp>
#include <engine/Simulator.hpp>
#include <engine/ModFiles.hpp>
#include <landscapedef/LandscapeDefinitions.hpp>
#include <landscapemap/LandscapeMaps.hpp>
#include <tankai/TankAIAdder.hpp>
#include <tankai/TankAIStore.hpp>
#include <target/TargetContainer.hpp>
#include <server/ServerConsoleProgressCounter.hpp>
#include <server/ServerConsoleLogger.hpp>
#include <server/ServerConnectAuthHandler.hpp>
#include <server/ServerChannelManager.hpp>
#include <server/ServerFileServer.hpp>
#include <server/ServerLoadLevel.hpp>
#include <server/ServerRegistration.hpp>
#include <server/ServerLog.hpp>
#include <server/ServerBrowserInfo.hpp>
#include <server/ServerCommon.hpp>
#include <server/ServerBanned.hpp>
#include <server/ServerMain.hpp>
#include <server/ScorchedServer.hpp>
#include <server/ServerState.hpp>
#include <server/ServerTimedMessage.hpp>
#include <server/ServerParams.hpp>
#include <SDL/SDL.h>

#include <igd/igd.hpp>

#ifdef S3D_SERVER
#include <webserver/ServerWebServer.hpp>
#endif

static Clock serverTimer;

static void serverMain(ProgressCounter *counter)
{
	ScorchedServerSettingsOptions settings(
		ServerParams::instance()->getServerFile(),
		ServerParams::instance()->getRewriteOptions(),
		ServerParams::instance()->getWriteFullOptions());

	// Create the server states
	if (!ScorchedServer::instance()->startServer(
		settings,
		false, counter)) exit(64);

	// Try to start the server
	if (!ScorchedServer::instance()->getContext().getNetInterface().start(
		ScorchedServer::instance()->getOptionsGame().getPortNo()) ||
		!ServerBrowserInfo::instance()->start())
	{
		S3D::dialogExit("Scorched3D Server", 
			S3D::formatStringBuffer("Failed to start the server.\n\n"
			"Could not bind to the server ports.\n"
			"Ensure the specified ports (%i, %i) do not conflict with any other program.",
			ScorchedServer::instance()->getOptionsGame().getPortNo(),
			ScorchedServer::instance()->getOptionsGame().getPortNo() + 1));
	}

	// Try to update the route to add the external port mapping
	if (ScorchedServer::instance()->getOptionsGame().getUseUPnP())
	{
		igd pnpigd;
		pnpigd.sendInitialRequest(ScorchedServer::instance()->getOptionsGame().getPortNo());
	}

	// Contact the registration server
 	if (ScorchedServer::instance()->getOptionsGame().getPublishServer()) 
	{
		ServerRegistration::instance()->start();
	}

#ifdef S3D_SERVER
	if (ScorchedServer::instance()->getOptionsGame().getManagementPortNo() > 0)
	{
		ServerWebServer::instance()->start(
			ScorchedServer::instance()->getOptionsGame().getManagementPortNo());

		Logger::log(S3D::formatStringBuffer("Management server running on url http://127.0.0.1:%i",
			ScorchedServer::instance()->getOptionsGame().getManagementPortNo()));
	}
#endif
	ServerLog::instance();

	std::string startTime = S3D::getStartTime();
	Logger::log(S3D::formatStringBuffer("Server started : %s", startTime.c_str()));
}

void serverLoop(fixed timeDifference)
{
	Logger::processLogEntries();

	// Main server loop:
	if (!ScorchedServer::serverStarted() ||
		!ScorchedServer::instance()->getContext().getNetInterfaceValid())
	{
		return;
	}
		
		ScorchedServer::instance()->getNetInterface().processMessages();
#ifdef S3D_SERVER
		{
			ServerBrowserInfo::instance()->processMessages();
			ServerWebServer::instance()->processMessages();
		}
#endif

		ScorchedServer::instance()->getSimulator().simulate();
		ScorchedServer::instance()->getServerState().simulate(timeDifference);

		ScorchedServer::instance()->getServerConnectAuthHandler().processMessages();
		ScorchedServer::instance()->getServerFileServer().simulate();
		ScorchedServer::instance()->getServerChannelManager().simulate(timeDifference);
		ScorchedServer::instance()->getTimedMessage().simulate();

		if (timeDifference > 5)
		{
			Logger::log(
				S3D::formatStringBuffer( "Warning: Server loop took %.2f seconds", timeDifference.asDouble() )
			);
		}
}

void consoleServer()
{
	ServerConsoleProgressCounter::instance();
	ServerConsoleLogger serverConsoleLogger;
	ServerCommon::startFileLogger(ServerParams::instance()->getServerFile());
	serverMain(ServerConsoleProgressCounter::instance()->getProgressCounter());

	serverTimer.getTicksDifference();
	for (;;)
	{
		SDL_Delay(10);

		unsigned int ticksDifference = serverTimer.getTicksDifference();
		fixed timeDifference(true, ticksDifference * 10);
		serverLoop(timeDifference);

		if (ServerParams::instance()->getExitTime() > 0)
		{
			if ( ServerParams::instance()->getExitTime() < time( nullptr ) )
			{
				Logger::log("Exiting server due to exit time");
				Logger::processLogEntries();
				break;
			}
		}
	}

	ScorchedServer::instance()->stopServer();
}
