"""OGG playback through SDL, replacing the 32-bit FMOD DLL."""
from pathlib import Path
import os, threading, time, logging
from lyntin import exported
from lyntin.modules import modutils
os.environ.setdefault('PYGAME_HIDE_SUPPORT_PROMPT','1')
import pygame
ROOT=Path(__file__).resolve().parents[2]
volume=50
delay=0.07
_lock=threading.Lock()
_last_play=0.0
def getVolume(): return volume

def ensure_mixer():
    with _lock:
        if not pygame.mixer.get_init():
            pygame.mixer.init()
            pygame.mixer.set_num_channels(32)
def setVolume(v):
    global volume
    volume=max(0,min(100,int(v)))
    if pygame.mixer.get_init():
        for i in range(pygame.mixer.get_num_channels()): pygame.mixer.Channel(i).set_volume(volume/100)
def play(sound):
    global _last_play
    path=Path(sound)
    if not path.is_absolute(): path=ROOT/path
    ensure_mixer()
    with _lock:
        time.sleep(max(0,delay-(time.monotonic()-_last_play)))
        sample=pygame.mixer.Sound(str(path))
        channel=pygame.mixer.find_channel(True)
        channel.set_volume(volume/100)
        channel.play(sample)
        _last_play=time.monotonic()
def sound_cmd(ses,args,input):
    filename=args['filename']
    if args.get('input'): filename += ' '+args['input']
    try: play(ROOT/'sounds'/filename)
    except Exception:
        logging.exception('Sound playback failed')
        exported.write_message("Impossible de jouer le son : %s" % filename, ses)
    else:
        exported.write_message("Son joué : %s" % filename, ses)
def sounddelay_cmd(ses,args,input):
    global delay
    delay=max(0,float(args['delay']))
def soundvolume_cmd(ses,args,input):
    try:
        v=int(args['volume'])
        if not 0<=v<=100: raise ValueError()
        setVolume(v)
    except (ValueError,TypeError): exported.write_message('Volume : entier de 0 à 100.')
commands_dict={'sound':(sound_cmd,'filename input=', 'limitparsing=1'),'sounddelay':(sounddelay_cmd,'delay'),'soundvolume':(soundvolume_cmd,'volume')}
def load(): modutils.load_commands(commands_dict)
def unload():
    modutils.unload_commands(commands_dict)
    if pygame.mixer.get_init(): pygame.mixer.quit()
