import es
from es import server_var
import playerlib, gamethread, langlib
import os, random
from configobj import ConfigObj

class DownloadMngr:
	def __init__(self):
		self.data = []
	def reset(self):
		self.data = []
	def add(self, file):
		if not file:
			return False
		if not os.path.isfile(file):
			es.dbgmsg(0, "SVIP: Unable to found '%s'" % file)
			return False
		es.stringtable('downloadables', file)
		return True
	def addByFile(self, file):
		if not file:
			return 0
		if not os.path.isfile(file):
			es.dbgmsg(0, "SVIP: Unable to found '%s'" % file)
			return 0
		f = open(file)
		if not f:
			es.dbgmsg(0, "SVIP: Unable to read '%s'" % file)
			return 0
		lines = f.readlines()
		i = 0
		if lines:
			for line in lines:
				if len(line) < 12:
					continue
				line = line.strip()
				line_array = line.split(None, 1)
				line = line_array[0]
				if len(line) >= 12 and line[0:2] <> "//" and line[0:1] <> "#":
					if not line in self.data:
						i += 1
						self.data.append(line)
						es.stringtable('downloadables', line)
						#es.dbgmsg(0, "SVIP: Added Download: %s" % line)
			es.dbgmsg(0, "SVIP: Added '%i' Downloads" % i)
		f.close()
		return len(self.data)
	def reAdd(self):
		for file in self.data:
			es.stringtable('downloadables', file)
		es.dbgmsg(0, "SVIP: ReAdded '%i' Downloads" % len(self.data))
	def exists(self, file):
		return (file in self.data)
	def count(self):
		return len(self.data)
	def printAll(self):
		i = 0
		es.dbgmsg(0, " ")
		es.dbgmsg(0, "----------------SVIP----------------")
		es.dbgmsg(0, "Current Downloads: (%i)" % len(self.data))
		es.dbgmsg(0, " ")
		for file in self.data:
			i += 1;
			es.dbgmsg(0, "%i: %s" % (i, file))
		es.dbgmsg(0, "----------------SVIP----------------")
		es.dbgmsg(0, " ")
		
class Admins:
	data = []
	def __init__(self, defFile):
		self.file = defFile
		global data
		data = []
	def reset(self, defFile = None):
		global data
		data = []
		
		if defFile is not None:
			self.file = defFile
	def load(self):
		if not self.file:
			return 0
		if not os.path.isfile(self.file):
			es.dbgmsg(0, "SVIP: Unable to found '%s'" % self.file)
			return 0
		f = open(self.file)
		if not f:
			es.dbgmsg(0, "SVIP: Unable to read '%s'" % self.file)
			return 0
		lines = f.readlines()
		if lines:
			global data
			data = []
			for steamid in lines:
				if len(steamid) < 11:
					continue
				steamid = steamid.upper()
				steamid = steamid.strip()
				steamid_array = steamid.split(None, 1)
				steamid = steamid_array[0]
				if len(steamid) >= 11 and steamid[0:2] <> "//" and steamid[0:1] <> "#" and steamid[0:6] == "STEAM_":
					if not steamid in data:
						data.append(steamid)
						es.dbgmsg(0, "SVIP: Added Admin: %s" % steamid)
		f.close()
		return len(data)
	def save(topText = None, toFile = None):
		filetoSave = self.file
		if toFile is not None:
			filetoSave = toFile
			
		f = open(filetoSave, 'w')
		if not f:
			return False
			
		toWrite = ""
			
		if topText is not None:
			toWrite = topText
			
		for steamid in data:
			toWrite = "%s\n%s" % (toWrite, steamid)
			
		f.write(toWrite)
		f.close()
			
		es.dbgmsg(0, "SVIP: Admin file sucessfully saved to '%s'" % filetoSave)
		return True
	def getIndex(self, steamid):
		if not steamid:
			return -1
		return data.index(steamid.upper())
	def isAdmin(self, steamid):
		if not steamid:
			return False
			
		#steamid = steamid.upper()
		return (steamid.upper() in data)
	def count(self):
		return len(data)
	def addAdmin(self, steamid):
		if not steamid:
			return False
		global data
		steamid = steamid.upper()
		steamid = steamid.strip()
		if len(steamid) >= 11 and steamid[0:6] == "STEAM_":
			if not steamid in data:
				data.append(steamid)
				es.dbgmsg(0, "SVIP: Added Admin: %s" % steamid)
			return True
		
		return False
	def delAdmin(self, steamid):
		index = getIndex(steamid)
		if index == -1:
			return False
		global data
		data.remove(index)
		es.dbgmsg(0, "SVIP: Removed Admin: %s" % steamid)
		return True
	def printAll(self):
		i = 0
		es.dbgmsg(0, " ")
		es.dbgmsg(0, "----------------SVIP----------------")
		es.dbgmsg(0, "Current Admins: (%i)" % len(data))
		es.dbgmsg(0, " ")
		for steamid in data:
			i += 1;
			es.dbgmsg(0, "%i: %s" % (i, steamid))
		es.dbgmsg(0, "----------------SVIP----------------")
		es.dbgmsg(0, " ")
		
# all SVIP server variables are declared here for convenience 
svip_version	  		= es.ServerVar("svip_version",				"2.0", "Current SVIP version.") 
svip			  		= es.ServerVar("svip",  					1, "Is SVIP enabled or disabled.") 
svip_enable		  		= es.ServerVar("svip_enable",  				1, "Enable or Disable SVIP in game.") 
svip_model				= es.ServerVar("svip_model",  				"player/techknow/smith/smith.mdl", "Model to be used for the VIP, dont forget the downloads.") 
svip_bots_can_use_vip 	= es.ServerVar("svip_bots_can_use_vip",		0, "Allow bots be the VIP.") 
svip_speed				= es.ServerVar("svip_speed",				1.1, "Set VIP speed. 0 = Default") 
svip_health				= es.ServerVar("svip_health",				150, "Set VIP Health. 0 = Default") 
svip_armor				= es.ServerVar("svip_armor",				150, "Set VIP Armor. 0 = Default") 
svip_allow_buy			= es.ServerVar("svip_allow_buy",			0, "Allow vip to buy items/weapons.")
svip_allow_pickup		= es.ServerVar("svip_allow_pickup",			0, "Allow vip to pickup items/weapons.")
svip_allow_to_pickup	= es.ServerVar("svip_allow_to_pickup",		"hegrenade,flashbang,smokegrenade", "Set an list of items/weapons the VIP is allowed to pickup.")
svip_primary_weapon		= es.ServerVar("svip_primary_weapon",		"0", "Give a primary weapon to VIP. 0 = None")
svip_secondary_weapon	= es.ServerVar("svip_secondary_weapon",		"weapon_usp", "Give a secondary weapon to VIP. 0 = None")

svip_map_config			= es.ServerVar("svip_map_config",  			0, "Use custom configs for each map (addons/eventscripts/svip/cfg/maps/).") 
svip_min_t_players		= es.ServerVar("svip_min_t_players",  		2, "Min players on Ts Team for VIP mod works.") 
svip_min_ct_players		= es.ServerVar("svip_min_ct_players",  		2, "Min players on CTs Team for VIP mod works.") 
#svip_automake_rescue_zones = es.ServerVar("svip_automake_rescue_zones",  1, "When ON script will try search for Hostages Extract Zones and add them as Rescue Zones for VIP.") 
#svip_automake_rescue_zones_type = es.ServerVar("svip_automake_rescue_zones_type",  0, "Set what script do with Hostages Extract Zones when already not have/have rescue zones") 
svip_restrict_drop		= es.ServerVar("svip_restrict_drop",  		1, "Restrict VIP from drop weapons.") 
svip_rescue_time		= es.ServerVar("svip_rescue_time",  		180, "Set the timelimit for CTs rescue the VIP (in seconds) Min: 20.") 
svip_playable_maps		= es.ServerVar("svip_playable_maps",  		"as_", "Maps where SVIP can work (prefix only separated by ','). 0 = All maps") 
svip_slay_lose_team		= es.ServerVar("svip_slay_lose_team",  		1, "Slay all players on the lose team.") 
svip_score_for_ts_team	= es.ServerVar("svip_score_for_ts_team",  	2, "Score to add for Ts Team when vip die.") 
svip_score_for_cts_team	= es.ServerVar("svip_score_for_cts_team", 	2, "Money to add for Ts Team when vip die.") 
svip_money_for_ts_team	= es.ServerVar("svip_money_for_ts_team",  	2000, "Score to add for CTs Team when rescuew vip.") 
svip_money_for_cts_team	= es.ServerVar("svip_money_for_cts_team", 	1500, "Money to add for CTs Team when rescuew vip.")

_svip_temp				= es.ServerVar("_svip_temp", 				0, "An temp cvar for SVIP.")

info = es.AddonInfo() 
info.name     	= "Sn4k3 Vip Mod" 
info.basename 	= "SVIP"
info.version  	= str(svip_version)
info.url      	= "http://addons.eventscripts.com/addons/view/SVIP" 
info.description = "Vip Mod"
info.author   	= "sn4k3"
#info.contact  	= "Tiago_caza@hotmail.com"
#info.tags	= "svip,vip,assassination"


_svip_opt = {}
_svip_opt['zones'] = []
_svip_opt['game_options'] = {}
_svip_opt['game_options']['path'] = es.getAddonPath("svip") + "/"
_svip_opt['game_options']['game_path'] = str(es.ServerVar('eventscripts_gamedir')) 
_svip_opt['game_options']['config_path'] = _svip_opt['game_options']['path'] + "cfg/"
_svip_opt['game_options']['config_short_path'] = "addons/eventscripts/svip/cfg/"
_svip_opt['game_options']['data_path'] = _svip_opt['game_options']['path'] + "data/"
_svip_opt['game_options']['game_time'] = -99
_svip_opt['game_options']['score_limit'] = -99
_svip_opt['game_options']['round_end'] = False
_svip_opt['game_options']['can_run'] = False
_svip_opt['game_options']['ct_score'] = 0
_svip_opt['game_options']['t_score'] = 0
_svip_opt['game_options']['vip_userid'] = 0
_svip_opt['game_options']['vip_status'] = "Unknown"
_svip_opt['game_sounds'] = {
'vip_killed'	:	"sn4k3_scripts/svip/svip_killed.mp3",
'vip_rescue'	:	"sn4k3_scripts/svip/svip_rescue.mp3",
'protect_vip'	:	"radio/vip.wav"
}
"""
_svip_opt['dev_sounds'] = {
'menuselect' 	: "buttons/button14.wav", 		'menuexit' 		: "buttons/combine_button7.wav",
'menuback'		: "UI/buttonclickrelease.wav",	'menunext'		: "UI/buttonrollover.wav",
'restrict' 		: "buttons/button8.wav"
}
"""
_svip_mapdata = None
_svip_admins = Admins(_svip_opt['game_options']['config_path'] + "admins.txt")
_svip_lang = None

def reset(isLoad = False):
	global _svip_opt
	global _svip_mapdata
	svip_version.set(info.version)
	svip.set("1")
	mapname = str(es.ServerVar('eventscripts_currentmap'))
	
	es.stringtable('downloadables', "sound/"+_svip_opt['game_sounds']['vip_killed'])
	es.stringtable('downloadables', "sound/"+_svip_opt['game_sounds']['vip_rescue'])
	
	DownloadMngr().addByFile(_svip_opt['game_options']['config_path'] + "downloads.txt")
	if not os.path.isdir(_svip_opt['game_options']['data_path']):
		os.mkdir(_svip_opt['game_options']['data_path'])
	if not os.path.isdir(_svip_opt['game_options']['data_path']+"zones"):
		os.mkdir(_svip_opt['game_options']['data_path']+"zones")
	
	_svip_mapdata = ConfigObj(_svip_opt['game_options']['data_path'] + "zones/" + mapname + '.ini')
		
	if int(svip_rescue_time) > 20:
		_svip_opt['game_options']['game_time'] = int(svip_rescue_time)
	else:
		_svip_opt['game_options']['game_time'] = -99
		
	if len(str(svip_playable_maps)) < 2:
		setThis = True
	else:
		maps = str(svip_playable_maps).split(",")
		setThis = False
		for map in maps:
			if mapname.startswith(map.strip()):
				setThis = True
				break
	_svip_opt['game_options']['can_run'] = setThis
	
	if int(svip_map_config) > 0:
		mapfile = "%smaps/%s.cfg" % (_svip_opt['game_options']['config_path'], mapname)
		if os.path.isfile(mapfile):
			es.server.cmd("es_xmexec ..%s" % mapfile.replace(_svip_opt['game_options']['game_path'], '', 1))
	svip_resetZones()
	svip_load_admins()
	gamethread.cancelDelayed("repeat1s")
	
def requirements():
	if not es.exists("variable", "est_version"):
		return False
	return True
	
def cmdfilter(userid, args):
	if args[0].lower() == "drop":
		if userid == _svip_opt['game_options']['vip_userid']:
			if int(svip_restrict_drop) > 0:
				es.tell(userid, "#multi", "\x04SVIP:\x01 %s" % _svip_lang("vip drop", None, playerlib.getPlayer(userid).get("lang")))
				return False
	if args[0].lower() == "buy" or args[0].lower() == "autobuy" or args[0].lower() == "rebuy":
		if userid == _svip_opt['game_options']['vip_userid']:
			if int(svip_allow_buy) <= 0:
				return False
	return True

def load():
	global _svip_lang
	svip_enable.set(1)
	svip_version.makepublic() 
	svip_enable.makepublic() 
	svip.makepublic()
	
	if not requirements():
		es.dbgmsg(0, " ")
		es.dbgmsg(0, "----------------SVIP----------------")
		es.dbgmsg(0, "Eventscripts (ES): PASSED [%s]" % str(es.ServerVar("eventscripts_ver")))
		es.dbgmsg(0, "EsTools (EST):     FAIL")
		es.dbgmsg(0, " ")
		es.dbgmsg(0, "Script will be unloaded, because not meat the REQUIREMENTS!")
		es.dbgmsg(0, "Please repair or load missing requirement if you haveit")
		es.dbgmsg(0, "Fail requirement can be downloaded at:")
		es.dbgmsg(0, "http://forums.mattie.info/cs/forums/viewtopic.php?t=3413")
		es.dbgmsg(0, "----------------SVIP----------------")
		es.dbgmsg(0, " ")
		es.server.queuecmd("es_unload svip")
		return False
		
	_svip_lang = langlib.Strings(_svip_opt['game_options']['data_path'] + "language.ini")
	
	if not es.exists("command", "svip_reload_admins"):
		es.regcmd('svip_reload_admins', 'svip/svip_reload_admins', 'Reload admins.')
	if not es.exists("command", "svip_print_admins"):
		es.regcmd('svip_print_admins', 'svip/svip_print_admins', 'Print all admins.')
	#if not es.exists("command", "vip_escapezone"):
	#	es.regcmd('vip_escapezone', 'svip/vip_escapezone', 'Set escape zone 1.')
	if not es.exists("saycommand", "setzone"):
		es.regsaycmd('setzone', 'svip/svip_setzone', 'Set a rescue zone on player location.')
		
	es.server.cmd("alias None \" \";es_xmexec ../%ssvip_server.cfg;es_xmexec ../%son_load.cfg" % (_svip_opt['game_options']['config_short_path'], _svip_opt['game_options']['config_short_path']))
	es.addons.registerClientCommandFilter(cmdfilter)

	if len(str(es.ServerVar('eventscripts_currentmap'))) > 1:
		reset(True)

def unload():
	svip.set("0")
	es.server.cmd("es_xmexec ../%son_unload.cfg" % _svip_opt['game_options']['config_short_path'])
	es.unregsaycmd("setzone")
	es.addons.unregisterClientCommandFilter(cmdfilter)
	gamethread.cancelDelayed("repeat1s")
	svip_resetZones()
	
def es_map_start(event_var):
	reset()
	es.server.cmd("es_xmexec ../%son_newmap.cfg" % _svip_opt['game_options']['config_short_path'])

def player_activate(event_var):
	if event_var['es_steamid'] != "BOT":
		gamethread.delayed(10, delayed_funcs, ("welcome", event_var['userid']))

def player_say(event_var):
	if event_var['text'] == "viewzones":
		player = playerlib.getPlayer(event_var['userid'])
		if not svip_canRun():
			es.tell(event_var['userid'], "#multi", "\x04SVIP:\x01 %s" % _svip_lang("cant run mod", None, player.get("lang")))
			return None
		menutext = "SVIP v%s <-> By sn4k3\n \n----------------------" % info.version
		i = 0
		for zone in _svip_mapdata:
			i += 1
			menutext += "\n%i = %s" % (i, _svip_mapdata[zone])
		menutext += "\n----------------------\n"
		
		if i <= 0:
			es.tell(event_var['userid'], "#multi", "\x04SVIP:\x01 %s" % _svip_lang("no rescue zones", None, player.get("lang")))
		else:
			es.menu(0, event_var['userid'], menutext)

def round_start(event_var):
	global _svip_opt
	if not svip_canRun():
		return None
	_svip_opt['game_options']['round_end'] = False
	_svip_opt['game_options']['vip_userid'] = 0
	_svip_opt['game_options']['vip_status'] = "Unknown"
	
	if len(_svip_mapdata) <= 0:
		myPlayerList = playerlib.getPlayerList("#human")
		for userid in myPlayerList:
			es.tell(userid.userid, "#multi", "\x04SVIP:\x01 %s" % _svip_lang("no rescue zones", None, playerlib.getPlayer(userid.userid).get("lang")))
		return None
	
	if int(svip_rescue_time) > 20:
		_svip_opt['game_options']['game_time'] = int(svip_rescue_time)
	
	if checkTeams():
		_svip_temp.set(0)
		if int(svip_bots_can_use_vip) > 0:
			es.server.cmd("est_RandPlayer _svip_temp #c!d")
		else:
			es.server.cmd("est_RandPlayer _svip_temp #c!b!d")
		if int(_svip_temp) <= 0:
			es.dbgmsg(0, "SVIP: Error on trying make a VIP, invalid player")
			return None
			
		_svip_opt['game_options']['vip_status'] = "Alive"
		_svip_opt['game_options']['vip_userid'] = int(_svip_temp)
		es.server.cmd("est_StripPlayer %i 1;es_xgive %i weapon_knife;es_xgive %i item_nvgs" % (_svip_opt['game_options']['vip_userid'], _svip_opt['game_options']['vip_userid'], _svip_opt['game_options']['vip_userid']))
		if int(svip_health) > 0:
			es.setplayerprop(_svip_opt['game_options']['vip_userid'], "CBasePlayer.m_iHealth", int(svip_health))
		if float(svip_speed) > 0:
			es.setplayerprop(_svip_opt['game_options']['vip_userid'], "CBasePlayer.localdata.m_flLaggedMovementValue", float(svip_speed))
		if int(svip_armor) > 0:
			es.server.cmd("es_xgive %i item_assaultsuit;est_SetArmor %i %i" % (_svip_opt['game_options']['vip_userid'], _svip_opt['game_options']['vip_userid'], int(svip_armor)))
		if len(str(svip_model)) > 3:
			playerlib.getPlayer(_svip_opt['game_options']['vip_userid']).set("model", str(svip_model))
		if str(svip_primary_weapon)[0:7] == "weapon_":
			es.server.cmd("es_xgive %i %s;est_SetAmmo %i 1 500" % (_svip_opt['game_options']['vip_userid'], str(svip_primary_weapon), _svip_opt['game_options']['vip_userid']))
		if str(svip_secondary_weapon)[0:7] == "weapon_":
			es.server.cmd("es_xgive %i %s;est_SetAmmo %i 1 500" % (_svip_opt['game_options']['vip_userid'], str(svip_secondary_weapon), _svip_opt['game_options']['vip_userid']))
		tokens = {}
		tokens['name'] = es.getplayername(int(_svip_temp))
		myPlayerList = playerlib.getPlayerList("#ct")
		for userid in myPlayerList:
			es.tell(userid.userid, "#multi", "\x04SVIP:\x01 %s" % _svip_lang("ct vip announcement", tokens, playerlib.getPlayer(userid.userid).get("lang")))
			es.playsound(userid.userid, _svip_opt['game_sounds']['protect_vip'], 1.0)
		myPlayerList = playerlib.getPlayerList("#t")
		for userid in myPlayerList:
			es.tell(userid.userid, "#multi", "\x04SVIP:\x01 %s" % _svip_lang("t vip announcement", tokens, playerlib.getPlayer(userid.userid).get("lang")))
		gamethread.delayedname(1, "repeat1s", delayed_funcs, ("repeat1s"))
	else:
		myPlayerList = playerlib.getPlayerList("#human")
		for userid in myPlayerList:
			es.tell(userid.userid, "#multi", "\x04SVIP:\x01 %s" % _svip_lang("need players", None, playerlib.getPlayer(userid.userid).get("lang")))
	svip_drawZones(_svip_opt['game_options']['vip_userid'])

	
def round_end(event_var):
	global _svip_opt
	_svip_opt['game_options']['round_end'] = True
	gamethread.cancelDelayed("endround")

def player_disconnect(event_var):
	if int(event_var['userid']) == _svip_opt['game_options']['vip_userid']:
		myPlayerList = playerlib.getPlayerList("#human")
		for userid in myPlayerList:
			es.tell(userid.userid, "#multi", "\x04SVIP:\x01 %s" % _svip_lang("vip disconnect", None, playerlib.getPlayer(userid.userid).get("lang")))
		if not _svip_opt['game_options']['round_end']:
			gamethread.delayedname(3, "endround", delayed_funcs, ("endround"))

def player_death(event_var):
	global _svip_opt
	if event_var['es_userteam'] == "3":
		if int(event_var['userid']) == _svip_opt['game_options']['vip_userid']:
			if event_var['userid'] == event_var['attacker']:
				myPlayerList = playerlib.getPlayerList("#human")
				for userid in myPlayerList:
					es.tell(userid.userid, "#multi", "\x04SVIP:\x01 %s" % _svip_lang("vip suicide", None, playerlib.getPlayer(userid.userid).get("lang")))
			else:
				tokens = {}
				tokens['attackername'] = event_var['es_attackername']
				myPlayerList = playerlib.getPlayerList("#human")
				for userid in myPlayerList:
					es.tell(userid.userid, "#multi", "\x04SVIP:\x01 %s" % _svip_lang("vip killed", tokens, playerlib.getPlayer(userid.userid).get("lang")))
					es.playsound(userid.userid, "sn4k3_scripts/svip/svip_killed.mp3", 1.0)
			_svip_opt['game_options']['vip_status'] = "Assassinated"
			_svip_opt['game_options']['t_score'] += 1
			if int(svip_slay_lose_team) > 0:
				es.server.cmd("est_slay #c!d")
			if int(svip_score_for_ts_team) > 0:
				es.server.cmd("est_KillAdd #t +%i" % int(svip_score_for_ts_team))
			if int(svip_money_for_ts_team) > 0:
				es.server.cmd("est_CashAdd #t +%i" % int(svip_money_for_ts_team))
				
			es.event("initialize", "vip_killed")
			es.event("setint", "vip_killed", "userid", int(event_var['userid']))
			es.event("setint", "vip_killed", "attacker", int(event_var['attacker']))
			es.event("fire", "vip_killed")
			if not _svip_opt['game_options']['round_end']:
				gamethread.delayedname(3, "endround", delayed_funcs, ("endround"))
			svip_show_status_hud()

def item_pickup(event_var):
	if int(event_var['userid']) == _svip_opt['game_options']['vip_userid']:
		if int(svip_allow_pickup) <= 0:
			if not event_var['item'] in str(svip_allow_to_pickup) and not event_var['item'] in "knife;defuser;kevlar;assaultsuite;nvgs;%s;%s" % (str(svip_primary_weapon), str(svip_secondary_weapon)):
				es.server.cmd("est_DropWeapon %s %s" % (event_var['userid'], event_var['item']))
				tokens = {}
				tokens['item'] = event_var['item']
				es.tell(event_var['userid'], "#multi", "\x04SVIP:\x01 %s" % _svip_lang("vip invalid pickup", tokens, playerlib.getPlayer(event_var['userid']).get("lang")))

def est_box_trigger(event_var):
	if not event_var['boxname'].startswith("svip_rescue_zone"):
		return None
	svip_resetZones()
	global _svip_opt
	_svip_opt['game_options']['vip_status'] = "Rescued"
	es.setplayerprop(event_var['userid'], "CBasePlayer.m_iHealth", 10000)
	myPlayerList = playerlib.getPlayerList("#human")
	for userid in myPlayerList:
		es.tell(userid.userid, "#multi", "\x04SVIP:\x01 %s" % _svip_lang("vip rescue", None, playerlib.getPlayer(userid.userid).get("lang")))
		es.playsound(userid.userid, "sn4k3_scripts/svip/svip_rescue.mp3", 1.0)

	es.server.cmd("est_Freeze #l 1;est_StripPlayer %s 1" % event_var['userid'])
	if int(svip_slay_lose_team) > 0:
		es.server.cmd("est_slay #t!d")
	if int(svip_score_for_cts_team) > 0:
		es.server.cmd("est_KillAdd #c +%i" % int(svip_score_for_cts_team))
	if int(svip_money_for_cts_team) > 0:
		es.server.cmd("est_CashAdd #c %i" % int(svip_money_for_cts_team))
		
	es.event("initialize", "vip_escaped")
	es.event("setint", "vip_escaped", "userid", int(event_var['userid']))
	es.event("fire", "vip_escaped")
	if not _svip_opt['game_options']['round_end']:
		gamethread.delayedname(3, "endround", delayed_funcs, ("endround"))
	svip_show_status_hud()
	
def svip_show_status_hud():
	#if _svip_opt['game_options']['round_end']:
	#	return False
	tokens = {}
	tokens['time'] = ""
	if _svip_opt['game_options']['game_time'] > 0:
		tokens['time'] = str(_svip_opt['game_options']['game_time'])
	tokens['name'] = es.getplayername(_svip_opt['game_options']['vip_userid'])
	tokens['health'] = es.getplayerprop(_svip_opt['game_options']['vip_userid'], "CBasePlayer.m_iHealth")
	myPlayerList = playerlib.getPlayerList("#human")
	for userid in myPlayerList:
		tokens['state'] = _svip_lang(_svip_opt['game_options']['vip_status'].lower()+" text", None, userid.get("lang"))
		es.server.cmd("est_HSay %s SVIP %s" % (userid.userid, _svip_lang("status hud", tokens, userid.get("lang"))))
	return True

def svip_load_admins():
	_svip_admins.load()
	
def svip_print_admins():
	_svip_admins.printAll()
	
#def vip_escapezone():
#	es.server.cmd("asdasdasdasd;cvaoqw0'i;scajhgauidfa;iascuaisd;cahsfdas")
	
def svip_setzone():
	userid = es.getcmduserid()
	player = playerlib.getPlayer(userid)
	if es.getargc() < 2:
		es.tell(userid, "\x04Syntax:\x01 %s <zone (\x031\x01-\x034\x01)>" % es.getargv(0))
		return
	if not svip_canRun():
		es.tell(userid, "#multi", "\x04SVIP:\x01 %s" % _svip_lang("cant run mod", None, player.get("lang")))
		return
	steamid = es.getplayersteamid(userid)
	if not _svip_admins.isAdmin(steamid):
		es.tell(userid, "#multi", "\x04SVIP:\x01 %s (\x03%s\x01)" % (_svip_lang("deny admin", None, player.get("lang")), es.getargv(0)))
		return

	if playerlib.getPlayer(userid).get("isdead"):
		es.tell(userid, "#multi", "\x04SVIP:\x01 %s (\x03%s\x01)" % (_svip_lang("need be alive", None, player.get("lang")), es.getargv(0)))
		return
	x, y, z = es.getplayerlocation(userid)
	argv = int(es.getargv(1))
	if argv < 0 or argv > 4:
		es.tell(userid, "\x04Syntax:\x01 %s <zone (\x031\x01-\x034\x01)>" % es.getargv(0))
		return
	
	sizelen = len(_svip_mapdata)+1
	_svip_mapdata[str(sizelen)] = "%s %s %s" % (x,y,z)
	_svip_mapdata.write()
	es.msg("\x04SVIP:\x01 New rescue zone (\x03%i\x01)" % argv)
	
def svip_timeEnd():
	_svip_opt['game_options']['vip_status'] = "Time End"
	_svip_opt['game_options']['t_score'] += 1
	myPlayerList = playerlib.getPlayerList("#human")
	for userid in myPlayerList:
		es.tell(userid.userid, "#multi", "\x04SVIP:\x01 %s" % _svip_lang("vip timeend", None, playerlib.getPlayer(userid.userid).get("lang")))
	es.server.cmd("est_Freeze #l 1;est_StripPlayer %i 1" % _svip_opt['game_options']['vip_userid'])
	#if int(svip_slay_lose_team) > 0:
	#	es.server.cmd("est_slay #c!d")
	if int(svip_score_for_ts_team) > 0:
		es.server.cmd("est_KillAdd #t +%i" % int(svip_score_for_ts_team))
	if int(svip_money_for_ts_team) > 0:
		es.server.cmd("est_CashAdd #t +%i" % int(svip_money_for_ts_team))
				
	if not _svip_opt['game_options']['round_end']:
		gamethread.delayedname(3, "endround", delayed_funcs, ("endround"))
	svip_show_status_hud()
	
def svip_resetZones():
	global _svip_opt
	for zone in _svip_opt['zones']:
		es.server.cmd("est_Box_Remove %s" % zone)
	_svip_opt['zones'] = []
	
def svip_drawZones(userid):
	svip_resetZones()
	global _svip_opt
	i = 0
	for zone in _svip_mapdata:
		i += 1
		xyz = _svip_mapdata[zone].strip().split()
		_svip_opt['zones'].append("svip_rescue_zone%i" % i)
		es.server.cmd("est_Box_Trigger %i svip_rescue_zone%i \"%f %f %f\" \"%f %f %f\"" % (userid, i, float(xyz[0])-80, float(xyz[1])-50, float(xyz[2])-10, float(xyz[0])+80, float(xyz[1])+50, float(xyz[2])+10))
		
def svip_canRun():
	if _svip_opt['game_options']['can_run'] and int(svip_enable) > 0:
		return True
	return False

def endGame():
	userid = es.getuserid()
	es.server.cmd("es_xgive %s game_end;es_xfire %s game_end EndGame" % (userid,userid))

def checkTeams():
	if es.getplayercount(2) >= int(svip_min_t_players) and es.getplayercount(3) >= int(svip_min_ct_players):
		return True
	return False
	
def getPlayers(filter):
	myPlayerList = playerlib.getPlayerList(filter)
	players = []
	for userid in myPlayerList:
		players.append(userid.userid)
	return players
	
def delayed_funcs(name, userid = 0):
	global _svip_opt
	if int(userid) > 0:
		if not es.exists("userid", userid):
			return False
		
	if name == "repeat1s":
		if _svip_opt['game_options']['game_time'] > 0:
			_svip_opt['game_options']['game_time'] -= 1
			if _svip_opt['game_options']['game_time'] == 0 or _svip_opt['game_options']['game_time'] == -1:
				svip_timeEnd()
		svip_show_status_hud()
		if not _svip_opt['game_options']['round_end']:
			gamethread.delayedname(1, "repeat1s", delayed_funcs, ("repeat1s"))
		return True
	if name == "endround":
		if _svip_opt['game_options']['round_end']:
			return False
		es.ServerVar("sv_cheats").set(1)
		es.server.cmd("es_xdelayed 0.1 endround;es_xdelayed 0.2 es_xset sv_cheats 0")
		return True
	if name == "welcome":
		es.tell(userid, "\x04SVIP:\x03 VIP\x01 Mod\x01, version: \x03%s\n\x04SVIP:\x01 Written By:\x03 sn4k3\x01 AKA\x03 Tiago Conceicao\n\x04Visit:\x01 http://addons.eventscripts.com/addons/view/SVIP\n" % info.version)
		return True
	if name == "autorespawn":
		if playerlib.getPlayer(userid).attributes['isdead']: # user is dead
			es.server.cmd("est_spawn %i" % int(userid))
		return True