import es
import random
import os
import gamethread
import cPickle
import threading
import urllib2
import langlib
#############################
#                           #
#     START OF CONFIG       #
#                           #
#############################

# Pfad fuer die Sounds der Terrors
# Path for the sounds of terrors

resPfadT = 'res/acbrother/T'


# Pfad fuer die Sounds der Counters
# Path for the sounds of counters

resPfadCT = 'res/acbrother/CT'


# Unterbricht laufende Sounds, an = 1 , aus = 0 (funktioniert nicht  perfekt)
# Disrupt playing sounds, on = 1 , off = 0 (works not perfectly)

resBreaker = 0


# Lautstaerkenregelung von 0.1 -1.0
# volume control from 0.1 - 1.0 

resVolume = 0.8	


# Wenn auf dem Server Gungame laeuft, ja = 1 , nein = 0  (funktioniert nur mit ES Gungame)
# If GunGame runs on Server, yes = 1 , no = 0  (Works only with ES Gungame)

resGunGame = 0


# spieler duerfen sound ein- und auschalten.
# Allow players to enable and disable sounds 

resOnOff = 1


# Befehl zum ein- uns auschalten der Sounds
# Command to enable and disable the sounds

resOnOffcommand = '!res'


# Alle x runden Werbung fuer resOnOffcommand. 0 = aus
# All x round advertising for resOnOffcommand. 0 = aus

resAdvtOnOffcommand = 60


# Team spezifische Sounds, an = 1 , aus = 0
# Team specific sounds, on = 1 , off = 0

resTeamS = 1		


# Zufalls Sound bei unentschieden, an = 1 , aus = 0
# Random sound when a draw, on = 1 , off = 0

resDrawSound = 1		


# Jeder Spieler hoert einen andern Sound, an = 1 , aus = 0
# Each player hears another sound, on = 1 , off = 0

resRandomSound = 0


# Spielt Sounds in fester Reihenfolge. Deaktiviert resRandomSound und aktiviert resTeamS
# Playing sounds in a fixed sequence. ResRandomSound disabled and enabled resTeamS

resOrderSound = 0


# Spielt bekommen den Soundnamen angezeigt
# Shows the sound name

resFileName = 0			


# Updates checken, ja = 1 , nein = 0
# Update check, yes = 1 , no = 0

resUpdateCheck = 1


# Admins, die eine Info erhalten sollen wenn ein Update verfuegbar ist
# Admins who are to receive a notification when an update is available	

resUpdateAdmins = ''


#############################
#                           #
#      END OF CONFIG        #
#                           #
#############################

#########################################################################################
### Do not change anything under this line unless you know exectly what you are doing ###
###         Unter dieser Linie nichts veraendern ausser du weist was du da tust       ###
#########################################################################################

info = es.AddonInfo()
info.name = "Round End Sounds"
info.version = "2.03"
info.author = "FreeZ"
info.url = "http://gts-fun.de"
info.basename = "roundendsounds"
info.description = "Round End Sounds for CSS"
info.copyright = "2010 - 2120"

translation_file = langlib.Strings(es.getAddonPath("res") + "/translation.ini")

resSoundlist = {}
resSoundlistT = {}
resSoundlistCT = {}
resSoundsoff = {}
translationsini = {}

picklePfad = 'cstrike/addons/eventscripts/res/soundsoff.data'
current_version = float(info.version)



def load():
	global resGGWin
	global resSoundlistT
	global resSoundlistCT
	global lenT
	global lenCT
	global resRandomSound
	global resTeamS

	es.set(info.basename , info.version)
	es.makepublic(info.basename)

	try:
		unpickle()
		es.dbgmsg(0, '[RES] could load userdata')
	except:
		es.dbgmsg(0, '[RES] could not load userdata')

	resGGWin = 0

	resSoundlistT = os.listdir('%s/cstrike/sound/%s/' % (os.getcwd(),resPfadT))
	resSoundlistCT = os.listdir('%s/cstrike/sound/%s/' % (os.getcwd(),resPfadCT))

	if resOrderSound == 1:
		lenT = len(resSoundlistT)
		lenCT = len(resSoundlistCT)
		resRandomSound = 0
		resTeamS = 1

def es_map_start(ev):
	global resGGWin
	global counterT
	global counterCT
	global roundcounter

	counterT = -1
	counterCT = -1

	download()
	if resGunGame == 1:
		resGGWin = 0
	roundcounter = 0


def gg_win(ev):
	global resGGWin
	if resGunGame == 1:
		resGGWin = 1

def round_end(ev):	
	pickle()
	if resBreaker == 0:
		gamethread.delayed(.2, playpreparation, (ev["winner"]))
	elif resBreaker == 1:
		gamethread.delayed(.1, es.cexec_all, ('play 0'))
		gamethread.delayed(.2, playpreparation, (ev["winner"]))

def round_start(ev):
	global lenT
	global lenCT
	global winflag
	global counterT
	global counterCT
	global roundcounter
	
	if resOrderSound == 1:
		if winflag == 2:
			if counterT < lenT-1:
				counterT = counterT + 1
			else:
				counterT = 0
			

		elif winflag == 3:
			if counterCT < lenCT-1:
				counterCT = counterCT + 1
			else:
				counterCT = 0

	if resAdvtOnOffcommand-1 == roundcounter:
		translationsini['onoffcommand'] = str(resOnOffcommand)
		es.msg('#multi', translation_file('res onoff command', translationsini))
		roundcounter = 0
	else:
		roundcounter = roundcounter + 1


def playpreparation(winner):
	global winflag
	global counterT
	global counterCT

	if resGGWin == 0:
		if resTeamS == 0:
			resZahl = random.randint(1, 10)
			if resZahl <= 5:
				soundplayer(resPfadT,resSoundlistT, winner)

			elif resZahl >=6:
				soundplayer(resPfadCT,resSoundlistCT, winner)

		elif resTeamS == 1:
			if winner == "2":
				winflag = 2
				if resOrderSound == 1:
					soundplayer(resPfadT,resSoundlistT[counterT], winner)
				else:
					soundplayer(resPfadT,resSoundlistT, winner)

			elif winner == "3":
				winflag = 3
				if resOrderSound == 1:
					soundplayer(resPfadCT,resSoundlistCT[counterCT], winner)
				else:
					soundplayer(resPfadCT,resSoundlistCT, winner)

			elif winner == "1":
				if resDrawSound == 1:
					resZahl = random.randint(1, 10)
					if resZahl <= 5:
						soundplayer(resPfadT,resSoundlistT, winner)
					elif resZahl >=6:
						soundplayer(resPfadCT,resSoundlistCT, winner)


def soundplayer(resPfad,resSoundlist, winner):
	sound = random.choice(resSoundlist)

	#es.msg("#multi", '#green DEBUG %s' % (resSoundlist))
	for player in es.getUseridList():
		if es.getplayersteamid(player) not in resSoundsoff:
			if resRandomSound == 1:
				randomchoice = random.choice(resSoundlist)
        			es.playsound(player, resPfad + "/"  + randomchoice, resVolume)
				if resFileName == 1:
					translationsini['filename'] = str(randomchoice).replace(".mp3","").replace(".wav","")
					es.tell(player, '#multi',translation_file('res file name', translationsini))
			else:
				if resOrderSound == 1:
					if winner == "1":
						randomchoice = random.choice(resSoundlist)
						es.playsound(player, resPfad + "/"  + randomchoice, resVolume)
						if resFileName == 1:
							translationsini['filename'] = str(randomchoice).replace(".mp3","").replace(".wav","")
							es.tell(player, '#multi',translation_file('res file name', translationsini))
					else:
						es.playsound(player, resPfad + "/"  + resSoundlist, resVolume)
						if resFileName == 1:
							translationsini['filename'] = str(randomchoice).replace(".mp3","").replace(".wav","")
							es.tell(player, '#multi',translation_file('res file name', translationsini))
				else:
					es.playsound(player, resPfad + "/"  + sound, resVolume)
					if resFileName == 1:
						translationsini['filename'] = str(randomchoice).replace(".mp3","").replace(".wav","")
						es.tell(player, '#multi',translation_file('res file name', translationsini))
				

def player_say(ev):

	if resOnOff == 1:
		if ev['text'] == resOnOffcommand:
			if ev['es_steamid'] not in resSoundsoff:
				resSteamid = ev['es_steamid']
				resSoundsoff[resSteamid] = 1
				es.tell(ev['userid'], '#multi', translation_file('res off message', translationsini))
			else:
				del resSoundsoff[ev['es_steamid']]
				es.tell(ev['userid'], '#multi', translation_file('res on message', translationsini))


def download():
	for i in range(0, len(resSoundlistT)):
		if resSoundlistT[i].endswith('wav') or resSoundlistT[i].endswith('mp3'):
			es.stringtable('downloadables', 'sound/%s/%s' %(resPfadT, resSoundlistT[i]))  
	for i in range(0, len(resSoundlistCT)):
		if resSoundlistCT[i].endswith('wav') or resSoundlistCT[i].endswith('mp3'):
			es.stringtable('downloadables', 'sound/%s/%s' %(resPfadCT, resSoundlistCT[i]))


def pickle():
	'''save data'''
	f = file(picklePfad, 'w')
	cPickle.dump(resSoundsoff, f)
	f.close()


def unpickle():
	global gjJoins
    
	'''get data back'''
	f = file(picklePfad)
	resSoundsoff = cPickle.load(f)
	f.close()


def player_activate(ev):
	global new_version

	updatecheck().start()
	steamid = ev["es_steamid"]
	if resUpdateCheck == 1:
		if steamid in resUpdateAdmins:
			if new_version != current_version:
				translationsini['current_version'] = str(current_version)
				translationsini['new_version'] = str(new_version)
				es.tell(ev['userid'], '#multi', '#lightgreen-----------------------------------------')
				es.tell(ev['userid'], '#multi', translation_file('update message', translationsini))
				es.tell(ev['userid'], '#multi', translation_file('download update message', translationsini))
				es.tell(ev['userid'], '#multi', '#lightgreen-----------------------------------------')
				es.tell(ev['userid'], '#multi', translation_file('update message', translationsini))
				es.tell(ev['userid'], '#multi', translation_file('download update message', translationsini))
				es.tell(ev['userid'], '#multi', '#lightgreen-----------------------------------------')



class updatecheck(threading.Thread):
	def run(self):
		global new_version
		version_data = urllib2.urlopen("http://gts-fun.de/addons_ev/res/res.php").read()
		new_version = float(version_data)
