import random

from direct.showbase.Audio3DManager import Audio3DManager
from panda3d.core import AudioSound, NodePath

from helper import base, PAUSED

SFX_MUTE = False
MUSIC_MUTE = False

audio3d = Audio3DManager(base.sfxManagerList[0], base.camera)
audio3d.set_distance_factor(6)
audio3d.detachListener()
music = base.loader.load_music('sfx/LD41.mp3')
shouting = base.loader.load_sfx('sfx/talking.mp3')
crumbling = audio3d.load_sfx('sfx/crumble.wav')
punches = [audio3d.load_sfx('sfx/punches/%d.wav'%i) for i in range(11)]
for p in punches:
    p.set_volume(0.3)

music.set_volume(0.5)
shouting.set_volume(0)
crumbling.set_volume(0)
shouting.set_loop(True)
music.set_loop(True)
crumbling.set_loop(True)
music.play()
crumble_source = NodePath('crumble source')
audio3d.attach_sound_to_object(crumbling, crumble_source)
crumble_source.reparent_to(base.render)
crumbling.play()
shouting.play()


def sfx_mute(value=None):
    global SFX_MUTE
    if value is None:
        value = not SFX_MUTE
    SFX_MUTE = value
    if value:
        for sound in punches + [crumbling, shouting]:
            sound.set_volume(0)
    else:
        for sound in punches:
            sound.set_volume(0.3)
        crumbling.set_volume(1 if _crumbling else 0)
        shouting.set_volume(0.3 if _shouting else 0)


def music_mute(value=None):
    global MUSIC_MUTE
    if value is None:
        value = not MUSIC_MUTE
    MUSIC_MUTE = value
    if value:
        music.set_volume(0)
    else:
        music.set_volume(0.25 if PAUSED[0] else 0.5)


_shouting = False


def shout(value:bool):
    global _shouting
    _shouting = value
    if SFX_MUTE:
        return
    shouting.set_volume(0.3 if value else 0)


def punch(source_np, building=False):
    p = random.choice(punches)
    if (not source_np) or source_np.is_empty():
        source_np = base.render
    audio3d.attach_sound_to_object(p, source_np)
    if SFX_MUTE:
        return
    p.play()


_last_crumble_id = -1
_crumbling = False


def crumble(pos, id):
    global _last_crumble_id
    global _crumbling
    _last_crumble_id = id
    _crumbling = True
    crumble_source.set_pos(pos)
    if SFX_MUTE:
        return
    crumbling.set_volume(1)


def uncrumble(id):
    global _crumbling
    if id != _last_crumble_id:
        return
    crumbling.set_volume(0)
    _crumbling = False
