import os
import sys
from typing import Self

#"pip install pygame-ce"
with open( os.devnull, "w" ) as f:
	oldstdout=sys.stdout; sys.stdout=f; import pygame; sys.stdout=oldstdout

from . import config



class PlayableSound:
	def __init__( self:Self, path:str, volume:float ):
		self.backing = pygame.mixer.Sound(path)
		self.backing.set_volume(volume)

		self._channels:list[pygame.mixer.Channel] = []

	def start( self:Self, loops:int=0, volume:float=1.0 ):
		self._channels = [ channel for channel in self._channels if channel.get_busy() ]

		channel = pygame.mixer.find_channel()
		if channel == None: return
		channel.set_volume(volume)
		channel.play( self.backing, loops )

		self._channels.append(channel)
	def stop( self:Self ):
		for channel in self._channels:
			channel.stop()
		self._channels.clear()

	def is_playing( self:Self ):
		return len(self._channels) != 0



class Sounds:
	def __init__( self:Self ):
		self.sounds:list[PlayableSound] = []
		def _fx( relpath:str, volume_factor:float=1.0 ):
			snd = PlayableSound( config.MAIN_DIR+relpath, config.volume_fx*volume_factor )
			self.sounds.append(snd)
			return snd

		self.item_gem    = _fx("data/audio/gem.ogg" )
		self.item_star   = _fx("data/audio/star.ogg")
		self.item_lifeup = _fx( "data/audio/life_up.wav", 0.8 )

		self.ticking = _fx("data/audio/ticking.ogg")

		self.wall_hedge = _fx("data/audio/wall_hedge.ogg")
		self.wall_metal = _fx("data/audio/wall_metal.ogg")

		self.lasers = _fx( "data/audio/laser.wav", 0.2 )

		self.explode = _fx("data/audio/explode.ogg")

sounds:Sounds|None = None

def init  ():
	global sounds
	sounds = Sounds()
def deinit():
	global sounds
	del sounds



def stop_all():
	for snd in sounds.sounds:
		snd.stop()

def update_volumes():
	for snd in sounds.sounds:
		snd.backing.set_volume(config.volume_fx)
