package net.minecraft.client.sounds;

import net.minecraft.client.resources.sounds.SimpleSoundInstance;
import net.minecraft.sounds.Music;
import net.minecraft.util.Mth;
import javax.annotation.Nullable;
import net.minecraft.client.resources.sounds.SoundInstance;
import net.minecraft.client.Minecraft;
import java.util.Random;

public class MusicManager {
    private final Random random;
    private final Minecraft minecraft;
    @Nullable
    private SoundInstance currentMusic;
    private int nextSongDelay;
    
    public MusicManager(final Minecraft dlx) {
        this.random = new Random();
        this.nextSongDelay = 100;
        this.minecraft = dlx;
    }
    
    public void tick() {
        final Music aci2 = this.minecraft.getSituationalMusic();
        if (this.currentMusic != null) {
            if (!aci2.getEvent().getLocation().equals(this.currentMusic.getLocation()) && aci2.replaceCurrentMusic()) {
                this.minecraft.getSoundManager().stop(this.currentMusic);
                this.nextSongDelay = Mth.nextInt(this.random, 0, aci2.getMinDelay() / 2);
            }
            if (!this.minecraft.getSoundManager().isActive(this.currentMusic)) {
                this.currentMusic = null;
                this.nextSongDelay = Math.min(this.nextSongDelay, Mth.nextInt(this.random, aci2.getMinDelay(), aci2.getMaxDelay()));
            }
        }
        this.nextSongDelay = Math.min(this.nextSongDelay, aci2.getMaxDelay());
        if (this.currentMusic == null && this.nextSongDelay-- <= 0) {
            this.startPlaying(aci2);
        }
    }
    
    public void startPlaying(final Music aci) {
        this.currentMusic = SimpleSoundInstance.forMusic(aci.getEvent());
        if (this.currentMusic.getSound() != SoundManager.EMPTY_SOUND) {
            this.minecraft.getSoundManager().play(this.currentMusic);
        }
        this.nextSongDelay = Integer.MAX_VALUE;
    }
    
    public void stopPlaying() {
        if (this.currentMusic != null) {
            this.minecraft.getSoundManager().stop(this.currentMusic);
            this.currentMusic = null;
        }
        this.nextSongDelay += 100;
    }
    
    public boolean isPlayingMusic(final Music aci) {
        return this.currentMusic != null && aci.getEvent().getLocation().equals(this.currentMusic.getLocation());
    }
}
