package audio

import (
	"slices"

	rl "github.com/gen2brain/raylib-go/raylib"
)

type audio struct {
	id  SoundID
	snd rl.Sound
}

type Manager struct {
	library *Library
	active  []audio
	paused  bool
}

func (sm *Manager) Load(library *Library) {
	sm.library = library
}

func (sm *Manager) play(id SoundID, looping bool) {
	snd := sm.library.Get(id)

	alias := rl.LoadSoundAlias(*snd)
	alias.Stream.Buffer.Looping = looping

	sm.active = append(sm.active, audio{
		id:  id,
		snd: alias,
	})

	rl.PlaySound(alias)
}

func (sm *Manager) Play(id SoundID) {
	sm.play(id, false)
}

func (sm *Manager) PlayLooped(id SoundID) {
	sm.play(id, true)
}

func (sm *Manager) Stop(id SoundID) {
	sm.active = slices.DeleteFunc(sm.active, func(a audio) bool {
		if a.id == id {
			rl.StopSound(a.snd)
			rl.UnloadSoundAlias(a.snd)
			return true
		}
		return false
	})
}

func (sm Manager) IsPlaying(id SoundID) bool {
	return rl.IsSoundPlaying(*sm.library.Get(id))
}

// Pause all active sounds
func (sm *Manager) Pause() {
	sm.paused = true
	for _, audio := range sm.active {
		rl.PauseSound(audio.snd)
	}
}

// Resume all active sounds.
func (sm *Manager) Resume() {
	for _, audio := range sm.active {
		rl.ResumeSound(audio.snd)
	}
	sm.paused = false
}

func (sm *Manager) Update() {
	if sm.paused {
		return
	}

	active := sm.active[:0]

	for _, audio := range sm.active {
		if !rl.IsSoundPlaying(audio.snd) {
			rl.UnloadSoundAlias(audio.snd)
			continue
		}
		active = append(active, audio)
	}

	sm.active = active
}
