import javazoom.jl.decoder.JavaLayerException;
import javazoom.jl.player.Player;

import java.awt.List;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class SoundHandler {

    private static boolean soundOn = true;

    private static ArrayList<Thread> runningThreads = new ArrayList<Thread>();

    // Wenn fehler beim erstellen von .jar mit sound hier gucken
    private static HashMap<String, String> sounds = new HashMap<String, String>(Map.of(
            "hit", "./Sound/water-drip.mp3"
    ));

    public static void playSound(String soundName) {
        if (soundOn) {
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Player player = new Player(new FileInputStream(sounds.get(soundName)));
                        player.play();
                    } catch (JavaLayerException | FileNotFoundException e) {
                        e.printStackTrace();
                    }
                }
            });
            thread.start();
            runningThreads.add(thread);
        }
        for (Thread oldThread : runningThreads) {
                if (!oldThread.isAlive()) {

                    try {
                        oldThread.join();
                        runningThreads.remove(oldThread);
                        System.out.println("cleared thread");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }
            }
    }


    static void add(String soundName,  String path){
        sounds.put(soundName, path);
    }

    static void setSoundOn(boolean sound){
        soundOn= sound;
    }

}
