from os import path
import pygame

class SfxPygame:
	def __init__(self):
		self.sound = {}
	
	def LoadSound(self, soundname):
                self.sound[soundname] = pygame.mixer.Sound(path.join("resources", soundname + ".ogg"))
	
	def Sound(self, soundname):
		return SoundObj(self.sound[soundname], soundname)
	
	def PlaySound(self, soundname, volume=1):
		# print "play", soundname, volume,
		ch = self.sound[soundname].play(0)
		if ch:
			#print "on channel", ch
			ch.set_volume(volume)
		else:
			#print "no channel"
			pass
	
	def StopAllSounds(self):
		# print "stopping all sounds"
		for s in self.sound:
			self.sound[s].stop()
	
	def SetVolume(self, soundname, volume):
		#print "setting volume of", soundname, "to", volume
		self.sound[soundname].set_volume(volume)

class SoundObj:
	def __init__(self, sound, name):
		self.sound = sound
		self.channel = None
		self.volume = 1
		self.name = name
	
	def IsPlaying(self):
		return self.channel and self.channel.get_sound() == self.sound and self.channel.get_busy()
	
	def Play(self, loop=True):
		#print "play", self.name,
		if not self.IsPlaying():
			if loop:
				self.channel = self.sound.play(-1)
			else:
				self.channel = self.sound.play(0)
			if self.channel:
				self.channel.set_volume(self.volume)
				#print "on channel", self.channel,
			else:
			#	print " - no channel!!!",
				pass
		# print

	def Stop(self):
		#print "stopping", self.name, "on channel", self.channel
		if self.IsPlaying():
			self.channel.stop()
	
	def SetVolume(self, volume):
		#print "setting volume on", self.name, "to", volume, "on channel", self.channel
		self.volume = volume
		if self.channel:
			self.channel.set_volume(volume)

sfx = SfxPygame()

if not pygame.mixer.get_init():
	class EmptySound(SoundObj):
		def __init__(self):
			SoundObj.__init__(self, None, "")
		
		def Play(self, loop=True):
			pass
	
	def ReturnEmptySound(soundname):
		return EmptySound()
	
	def Nothing(*args, **kwargs):
		pass
	
	sfx.LoadSound = Nothing
	sfx.SetVolume = Nothing
	sfx.PlaySound = Nothing
	sfx.Sound = ReturnEmptySound


