package se.urmo.game.sound;

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import java.util.EnumMap;
import java.util.Map;

public class SoundManager {
    private final Map<SoundEffect, Clip> clips = new EnumMap<>(SoundEffect.class);
    private SoundEffect lastMunch = SoundEffect.MUNCH1;

    public SoundManager() {
        load(SoundEffect.START, "/sounds/start.wav");
        load(SoundEffect.SIREN, "/sounds/siren0.wav");
        load(SoundEffect.MUNCH1, "/sounds/eat_dot_0_fast.wav");
        load(SoundEffect.MUNCH2, "/sounds/eat_dot_1_fast.wav");
        load(SoundEffect.FRUIT, "/sounds/eat_fruit.wav");
        load(SoundEffect.GHOST_EATEN, "/sounds/eat_ghost.wav");
        load(SoundEffect.EXTRA_LIFE, "/sounds/extend.wav");
        load(SoundEffect.DEATH, "/sounds/death_0.wav");
    }

    private void load(SoundEffect id, String path) {
        try (AudioInputStream ais = AudioSystem.getAudioInputStream(getClass().getResource(path))) {
            Clip clip = AudioSystem.getClip();
            clip.open(ais);
            clips.put(id, clip);
        } catch (Exception e) {
            throw new RuntimeException("Failed to load sound: " + path, e);
        }
    }

    public void play(SoundEffect id) {
        Clip clip = clips.get(id);
        if (clip == null) return;
        if (clip.isRunning()) clip.stop();
        clip.setFramePosition(0);
        clip.start();
    }

    public void loop(SoundEffect id) {
        Clip clip = clips.get(id);
        if (clip == null) return;
        if (!clip.isRunning()) {
            clip.setFramePosition(0);
            clip.loop(Clip.LOOP_CONTINUOUSLY);
        }
    }

    public void stop(SoundEffect id) {
        Clip clip = clips.get(id);
        if (clip != null && clip.isRunning()) clip.stop();
    }

    // For dot munch alternation
    public void playMunch() {
        lastMunch = (lastMunch == SoundEffect.MUNCH1 ? SoundEffect.MUNCH2 : SoundEffect.MUNCH1);
        play(lastMunch);
    }
}

