import os

import aud

from .character import STEP_ACTION_LAYER

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

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

FADE_RATE = 1 / 100
MIN_VOLUME = 0.01
MAX_VOLUME = 1.0


class Track:
    def __init__(self, path):
        self.path = path
        file_factory = aud.Factory(path)
        self.factory = file_factory.volume(1).loop(-1)
        self.handle = None
        self.target_volume = MIN_VOLUME

    def play(self):
        if self.handle:
            raise ValueError("Already playing!")
        self.handle = device.play(self.factory)
        self.handle.volume = self.target_volume

    def interpolate_volume(self):
        lower = MIN_VOLUME
        upper = MAX_VOLUME
        if self.handle.volume < self.target_volume:
            diff = FADE_RATE
            upper = self.target_volume
        else:
            diff = -FADE_RATE
            lower = self.target_volume
        new_vol = self.handle.volume + diff
        new_vol = min(max(new_vol, lower), upper)
        self.handle.volume = new_vol

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


def music_factory(file_name):
    path = os.path.join(sounds_dir, file_name)
    return Track(path)


sounds = {
    'ambient': music_factory('Ambient.ogg'),
    'upbeat': music_factory('Upbeat.ogg'),
}


def init():
    sounds['ambient'].play()
    sounds['ambient'].target_volume = MAX_VOLUME
    sounds['upbeat'].play()
    sounds['upbeat'].target_volume = MIN_VOLUME


def update(c):
    manager = c.owner
    upbeat = manager['upbeat']
    sounds['upbeat'].target_volume = manager['upbeat']

    for sound in sounds.values():
        sound.interpolate_volume()


def message(c):
    manager = c.owner
    message_sensor = c.sensors[0]
    if not (message_sensor.triggered and message_sensor.positive):
        return
    manager['upbeat'] = float(message_sensor.bodies[-1])
