package assets

import (
	"bytes"
	"embed"
	"fmt"
	"io/fs"
	"log"

	"github.com/hajimehoshi/ebiten/v2/audio"
	"github.com/hajimehoshi/ebiten/v2/audio/wav"
)

//go:embed *
//go:embed */*
var embeddedFiles embed.FS
var sampleRate = 44100
var audioContext = audio.NewContext(sampleRate)
var songChoice = 2
var SongTracks = loadTracksForSong(songChoice)

func loadTracksForSong(sng int) map[int]*audio.Player {
	tempMap := make(map[int]*audio.Player)
	for i := 1; i <= 10; i++ {
		tempMap[i] = LoadWavAudioFile(fmt.Sprintf("audio/song0%d/track%02d.wav", sng, i), true)
	}

	return tempMap
}

var SFXLibrary = map[string]*audio.Player{
	"newLevel":    LoadWavAudioFile("audio/portal2.wav", false),
	"colourMatch": LoadWavAudioFile("audio/portal.wav", false),
	"gameOver":    LoadWavAudioFile("audio/gameOver.wav", false),
}

func LoadWavAudioFile(filePath string, loop bool) *audio.Player {

	audioData, err := fs.ReadFile(embeddedFiles, filePath)
	if err != nil {
		log.Fatal(err)
	}

	stream, err := wav.DecodeWithSampleRate(sampleRate, bytes.NewReader(audioData))
	if err != nil {
		log.Fatalf("failed to decode audio: %v", err)
	}

	var player *audio.Player

	if loop {
		lengthOfAudioData := int64(len(audioData))
		loopingStream := audio.NewInfiniteLoop(stream, lengthOfAudioData)
		player, err = audioContext.NewPlayer(loopingStream)

	} else {
		player, err = audioContext.NewPlayer(stream)
	}

	if err != nil {
		log.Fatal(err)
	}
	return player

}

func SilenceSongTracks() {
	for _, song := range SongTracks {
		song.SetVolume(0)
	}
}
