import os

import aud

from .character import STEP_ACTION_LAYER

scripts_dir = os.path.dirname(__file__)
sounds_dir = os.path.join(scripts_dir, '..', 'sound')

device = aud.device()
device.volume = 1


class Sound:
    def __init__(self, path):
        self.path = path
        self.factory = aud.Factory(path)
        self.handle = None

    def play(self):
        if self.handle and self.handle.status:
            return
        self.handle = device.play(self.factory)

    def __str__(self):
        return 'Sound(%s)' % self.path


def sound_factory(file_name):
    path = os.path.join(sounds_dir, file_name)
    return Sound(path)


sounds = {
    'jump': sound_factory('MouthPopOpen.ogg'),
    'land': sound_factory('MouthPopClose.ogg'),
}


def jump(c):
    char_root = c.owner
    armature = char_root.children['arm']
    if not armature.isPlayingAction(STEP_ACTION_LAYER):
        return
    current_frame = armature.getActionFrame(STEP_ACTION_LAYER)
    if int(current_frame) == 3:
        sounds['jump'].play()
    elif int(current_frame) == 7:
        sounds['land'].play()
