#!/usr/bin/python -u

# Dedicated Control handler script for OpenLieroX
# (http://openlierox.sourceforge.net)

# TODO: Why don't we import dedicated_control_functions as this namespace? I don't get the point of current implementation.

import os, sys, time

sys.path.append(os.getcwd()+"/cfg") # Append cfg dir to Python imports search paths
sys.path.append(os.getcwd()+"/scripts") # Append current dir to Python imports search paths
import dedicated_control_functions # Low-level stuff
import dedicated_config  # Per-host config like admin password
ded = dedicated_control_functions # shortcut
cfg = dedicated_config # shortcut

## Global vars ##

## The game loop ##

ded.init()

ded.msg("GameState = %s" % str(ded.gameState))
ded.messageLog("Dedicated_control started",ded.LOG_INFO)

ded.startLobby()

ded.waitLobbyStarted()

ded.setvar("GameServer.ServerName", cfg.SERVER_NAME)

ded.setvar("GameServer.GameInfo.sWelcomeMessage", cfg.WELCOME_MESSAGE)
ded.setvar("GameServer.MaxPlayers", cfg.MAX_PLAYERS)

ded.setvar("GameServer.GameInfo.iGameMode", 0) # 0 - DM, 1 - Team DM
ded.setvar("GameServer.GameInfo.iLives", cfg.GAME_LIVES)
ded.setvar("GameServer.GameInfo.iKillLimit", cfg.GAME_MAX_KILLS)
ded.setvar("GameServer.GameInfo.fTimeLimit", cfg.GAME_MAX_TIME)
ded.setvar("GameOptions.Advanced.WeaponSelectionMaxTime", cfg.WEAPON_SELECTION_TIME)

ded.selectNextPreset()

# nice state-machine for dedicated server
while ded.gameState != ded.GAME_QUIT:

	time.sleep(1)

	ded.oldGameState = ded.gameState
	# It's possible to create a deadlock here, depending on how you act on the signals.(Perhaps thread it as albert suggests?)
	# Loops through all the signals, and once we are out of all signals, continue on to the standard loop
	while ded.signalHandler(ded.getSignal()):
		pass # Continue with the next iteration

	if not ded.scriptPaused:
		ded.controlHandler()

ded.messageLog("GameState is QUIT. Exiting.",LOG_INFO)
sys.exit() # Kill the stdin-input thread
