#!/usr/bin/python -u
# The Python presets are detected from non-Python ones by first line which shouild contain "python" string

setvar( "GameOptions.LastGame.LevelName", "LieroFactory(Revisited).lxl" )
setvar( "GameServer.GameInfo.sMapFile",   "LieroFactory(Revisited).lxl" )
setvar( "GameServer.GameInfo.sMapName",   "LFr" )

setvar( "GameOptions.LastGame.ModName",   "Classic" )
setvar( "GameServer.GameInfo.sModDir",    "Classic" )
setvar( "GameServer.GameInfo.sModName",   "Classic" )

setvar( "GameOptions.LastGame.LoadingTime", 100 )
setvar( "GameServer.GameInfo.iLoadingTimes", 100 )

setvar( "GameServer.WeaponRestrictionsFile", "cfg/presets/100 LT.wps" )

setvar( "GameServer.ServerName", "Dedicated - TeamArena" )

setvar("GameServer.GameInfo.iGameMode", 1) # Required for this gamemode
setvar("GameOptions.LastGame.GameType", 1)

setvar("GameServer.GameInfo.iLives", 0) # Required for this gamemode
setvar("GameOptions.LastGame.Lives", 0)

setvar("GameOptions.LastGame.RespawnInWaves", 1) # Required for this gamemode

setvar("GameOptions.LastGame.RespawnGroupTeams", 1) # Required for this gamemode

setvar("GameOptions.Advanced.CountTeamkills", 0)

def controlHandlerTeamArena():

	RoundsToWin = 5 # You may change this var
	WaitInLobbyBeforeNextRound = cfg.WAIT_BEFORE_GAME # You may change this var, it can be zero

	global worms, gameState, lobbyChangePresetTimeout, lobbyWaitBeforeGame, lobbyWaitAfterGame, lobbyWaitGeneral, lobbyEnoughPlayers, oldGameState, sentStartGame
	global TeamArenaScore, TeamArenaRound
	try:
		temp = TeamArenaScore
	except NameError:
		TeamArenaScore = [0,0,0,0]
	try:
		temp = TeamArenaRound
	except NameError:
		TeamArenaRound = -1
	
	if gameState == GAME_LOBBY:

		# Do not check ping in lobby - it's wrong
		# End round if some team reaches max score or if only 1 worm left
		for i in range(4):
			if TeamArenaScore[i] >= RoundsToWin or ( TeamArenaRound >= 0 and getNumWorms() <= 1 ):
				msg = "Final score: blue %i red %i" % ( TeamArenaScore[0], TeamArenaScore[1] )
				if cfg.MAX_TEAMS >= 3:
					msg += " green %i" % TeamArenaScore[2]
				if cfg.MAX_TEAMS >= 4:
					msg += " yellow %i" % TeamArenaScore[3]
				chatMsg(msg)
				TeamArenaRound = -1
				TeamArenaScore = [0,0,0,0]

		if TeamArenaRound >= 0:

			msg = "Round %i: blue %i red %i" % ( TeamArenaRound, TeamArenaScore[0], TeamArenaScore[1] )
			if cfg.MAX_TEAMS >= 3:
				msg += " green %i" % TeamArenaScore[2]
			if cfg.MAX_TEAMS >= 4:
				msg += " yellow %i" % TeamArenaScore[3]

			if lobbyWaitBeforeGame == WaitInLobbyBeforeNextRound:
				chatMsg(msg)
			lobbyWaitBeforeGame -= 1

			if lobbyWaitBeforeGame <= 0 and getNumWorms() >= cfg.MIN_PLAYERS:
				if not sentStartGame:
					for i in worms.keys():
						if worms[i].iID == -1:
							continue
						worms[i].Lives = 0
					startGame()
					chatMsg(msg)

		else:
		
			lobbyChangePresetTimeout -= 1
    
			if oldGameState != GAME_LOBBY or lobbyChangePresetTimeout <= 0:
				lobbyChangePresetTimeout = cfg.PRESET_TIMEOUT
				selectNextPreset()
				lobbyEnoughPlayers = False # reset the state
				lobbyWaitGeneral = cfg.WAIT_BEFORE_SPAMMING_TOO_FEW_PLAYERS_MESSAGE
				lobbyWaitAfterGame = 0
				if oldGameState == GAME_PLAYING:
					lobbyWaitAfterGame = cfg.WAIT_AFTER_GAME
    
			lobbyWaitAfterGame -= 1
    
			if lobbyWaitAfterGame <= 0:
    
				lobbyWaitGeneral -= 1
    
				if not lobbyEnoughPlayers and lobbyWaitGeneral <= 0:
					lobbyWaitGeneral = cfg.WAIT_BEFORE_SPAMMING_TOO_FEW_PLAYERS_MESSAGE
					chatMsg(cfg.TOO_FEW_PLAYERS_MESSAGE)
    
				if not lobbyEnoughPlayers and getNumWorms() >= cfg.MIN_PLAYERS: # Enough players already - start game
					lobbyEnoughPlayers = True
					chatMsg(cfg.WAIT_BEFORE_GAME_MESSAGE)
					lobbyWaitBeforeGame = cfg.WAIT_BEFORE_GAME
    
				if lobbyEnoughPlayers and getNumWorms() < cfg.MIN_PLAYERS: # Some players left when game not yet started
					lobbyEnoughPlayers = False
					chatMsg(cfg.TOO_FEW_PLAYERS_MESSAGE)
    
				if lobbyEnoughPlayers and not sentStartGame:
					lobbyWaitBeforeGame -= 1
					if lobbyWaitBeforeGame <= 0: # Start the game
    
						sendLobbyUpdate() # Update game mode info
						
						if not cfg.ALLOW_TEAM_CHANGE:
							counter = 0
							for w in worms.values():
								if w.iID != -1:
									setWormTeam( w.iID, counter % cfg.MAX_TEAMS )
									counter += 1
						
						for i in worms.keys():
							if worms[i].iID == -1:
								continue
							worms[i].Lives = 0
						
						TeamArenaRound = 0
						TeamArenaScore = [0,0,0,0]
						startGame()
						if cfg.ALLOW_TEAM_CHANGE:
							chatMsg(cfg.TEAM_CHANGE_MESSAGE)

	if gameState == GAME_WEAPONS:
	
		if getNumWorms() < cfg.MIN_PLAYERS: # Some players left when game not yet started
			gotoLobby()

	if gameState == GAME_PLAYING:

		checkMaxPing()

		teamAlive = [0,0,0,0]
		for i in worms.keys():
			if worms[i].iID == -1:
				continue
			if worms[i].Lives >= 0:
				teamAlive[worms[i].Team] += 1

		teamAliveCount = 0
		teamAliveIdx = -1
		for i in range(4):
			if teamAlive[i] > 0:
				teamAliveCount += 1
				teamAliveIdx = i
		if teamAliveCount == 1:
			TeamArenaRound += 1
			TeamArenaScore[teamAliveIdx] += 1
			lobbyWaitBeforeGame = WaitInLobbyBeforeNextRound
			gotoLobby()
		if teamAliveCount == 0:
			lobbyWaitBeforeGame = WaitInLobbyBeforeNextRound
			gotoLobby()
			
def adminCommandHelpTeamArena(wormid):
	privateMsg(wormid, "%sreset - resets TeamArena state" % cfg.ADMIN_PREFIX)

def parseAdminCommandTeamArena(wormid, cmd, params):
	global TeamArenaScore, TeamArenaRound
	try:
		temp = TeamArenaScore
		temp = TeamArenaRound
	except NameError:
		return False

	if cmd == "reset":
		gotoLobby()
		msg = "Final score: blue %i red %i" % ( TeamArenaScore[0], TeamArenaScore[1] )
		if cfg.MAX_TEAMS >= 3:
			msg += " green %i" % TeamArenaScore[2]
		if cfg.MAX_TEAMS >= 4:
			msg += " yellow %i" % TeamArenaScore[3]
		time.sleep(1)
		chatMsg(msg)
		TeamArenaRound = -1
		TeamArenaScore = [0,0,0,0]
		
		return True
	
	return False


def userCommandHelpTeamArena(wormid):
	privateMsg(wormid, "%sscore - prints TeamArena score" % cfg.USER_PREFIX)

def parseUserCommandTeamArena(wormid, cmd, params):
	global TeamArenaScore, TeamArenaRound
	try:
		temp = TeamArenaScore
		temp = TeamArenaRound
	except NameError:
		return False

	if cmd == "score":
		msg = "Round %i: blue %i red %i" % ( TeamArenaRound, TeamArenaScore[0], TeamArenaScore[1] )
		if cfg.MAX_TEAMS >= 3:
			msg += " green %i" % TeamArenaScore[2]
		if cfg.MAX_TEAMS >= 4:
			msg += " yellow %i" % TeamArenaScore[3]
		privateMsg(wormid, msg)
		
		return True
	
	return False

global controlHandler, adminCommandHelp_Preset, parseAdminCommand_Preset, userCommandHelp_Preset, parseUserCommand_Preset
controlHandler = controlHandlerTeamArena
adminCommandHelp_Preset = adminCommandHelpTeamArena
parseAdminCommand_Preset = parseAdminCommandTeamArena
userCommandHelp_Preset = userCommandHelpTeamArena
parseUserCommand_Preset = parseUserCommandTeamArena

sendLobbyUpdate() # Update game mode info
if cfg.ALLOW_TEAM_CHANGE:
	chatMsg(cfg.TEAM_CHANGE_MESSAGE)
