from functools import partial

from direct.gui.DirectButton import DirectButton
from direct.showbase.DirectObject import DirectObject

from global_stuff import *


title_music = base.loader.load_music('ld40_title.wav')
music = base.loader.load_music('ld40.wav')

current = title_music
muted = False

for m in (title_music, music):
    m.set_loop(True)


def mute():
    global muted
    if not muted:
        current.stop()
        muted = True
        music_button['text'] = 'music off'
    else:
        current.play()
        muted = False
        music_button['text'] = 'music on'


def change_music(music):
    global current
    current.stop()
    current = music
    if not muted:
        current.play()


sfx = [door_close_sfx, door_open_sfx, merge_sfx, place_wall_sfx]
sfx_muted = False


def mute_sfx():
    global sfx_muted
    if sfx_muted:
        door_open_sfx.set_volume(1)
        door_close_sfx.set_volume(1)
        place_wall_sfx.set_volume(0.2)
        merge_sfx.set_volume(0.2)
        sfx_muted = False
        sfx_button['text'] = 'sfx on'
    else:
        for s in sfx:
            s.set_volume(0)
        sfx_muted = True
        sfx_button['text'] = 'sfx off'


base.accept('mute_sfx', mute_sfx)


def mute_both():
    if muted == sfx_muted:
        base.messenger.send('mute_music')
        base.messenger.send('mute_sfx')
    if muted and not sfx_muted:
        base.messenger.send('mute_sfx')
    if not muted and sfx_muted:
        base.messenger.send('mute_music')


music_button = DirectButton(text="music on", parent=base.pixel2d, scale=15, pos=(1250, 0, -20),
                            command=lambda: base.messenger.send('mute_music'))
sfx_button = DirectButton(text="sfx on", parent=base.pixel2d, scale=15, pos=(1200, 0, -20),
                          command=lambda: base.messenger.send('mute_sfx'))

button_style(music_button)
button_style(sfx_button)


class EventHandler(DirectObject):
    def __init__(self):
        self.accept('level_select', partial(change_music, title_music))
        self.accept('level_selected', partial(change_music, music))
        self.accept('mute_music', mute)
        self.accept('m', mute_both)


EventHandler()