package de.miaurizius.jgame2d.core.handlers;

import de.miaurizius.jgame2d.core.Boot;

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.FloatControl;
import java.io.File;
import java.net.URL;
import java.util.logging.Level;

public class Sound {

    public Clip clip;
    URL[] soundURL = new URL[30];
    public Clip[] clips = new Clip[30];
    public FloatControl fc;
    public int volumeScale = 3;
    float volume;

    public Sound() {
        load(0, "assets/sounds/BlueBoyAdventure.wav");
        load(1, "assets/sounds/coin.wav");
        load(2, "assets/sounds/powerup.wav");
        load(3, "assets/sounds/unlock.wav");
        load(4, "assets/sounds/fanfare.wav");
        load(5, "assets/sounds/hitmonster.wav");
        load(6, "assets/sounds/receivedamage.wav");
        load(7, "assets/sounds/blocked.wav");
        load(8, "assets/sounds/levelup.wav");
        load(9, "assets/sounds/cursor.wav");
        load(10, "assets/sounds/burning.wav");
        load(11, "assets/sounds/cuttree.wav");
        load(12, "assets/sounds/gameover.wav");
        load(13, "assets/sounds/stairs.wav");
        load(14, "assets/sounds/sleep.wav");
        load(15, "assets/sounds/blocked.wav");
        load(16, "assets/sounds/parry.wav");
        load(17, "assets/sounds/speak.wav");
    }

    @Deprecated
    public void setFile(int i) {
        try {
            AudioInputStream ais = AudioSystem.getAudioInputStream(soundURL[i]);
            clip = AudioSystem.getClip();
            clip.open(ais);
        } catch (Exception e) {
            Boot.logger.log(Level.SEVERE, "Could not load Sound File: " + soundURL[i], e);
        }
    }

    // MANAGER
    private void load(int index, String path) {
        try {
            AudioInputStream ais = AudioSystem.getAudioInputStream(new File(path));
            clips[index] = AudioSystem.getClip();
            clips[index].open(ais); // Wird nur einmal gemacht!
        } catch (Exception e) {
            Boot.logger.log(Level.SEVERE, "Could not load Sound File: " + soundURL[index], e);
        }
    }
    public void stop() {
        clip.stop();
    }
    public void checkVolume() {
        switch(volumeScale) {
            case 0 -> volume = -80f;
            case 1 -> volume = -20f;
            case 2 -> volume = -12f;
            case 3 -> volume = -5f;
            case 4 -> volume = 1f;
            case 5 -> volume = 6f;
        }
        fc.setValue(volume);
    }

}
