-- Normal Battle Themes --

/*
	Console command
*/
local battletheme_cv = CV_RegisterVar{
	name = "pso_battletheme",
	defaultvalue = "none",
	flags = 0,
	PossibleValue = {none=0, publicenemy=1, lockandload=2, darkskies=3, returntoashes=4, asoulcantbecut=5, thetimehascome=6}
}

/*
	Only 6 songs for now, one for each zone.
*/
local battle_select = {
	"PE",
	"LAL",
	"MGDKSK",
	"MGRTOA",
	"MGSOUL",
	"TTHC",
}

/*
	Changes the blank song.
*/
addHook("MusicChange", function(oldname, newname, mflags, looping, position, prefadems, fadeinms)
	if not consoleplayer return end
	local music_change = false
	if newname == "battle" then
		if battle_select[battletheme_cv.value] then
			music_change = battle_select[battletheme_cv.value]
		end
	end
	return music_change
end)

local function handleBattleMusic()
	if not server.psorooms return end	-- wait til these are generated
	-- iterate in another order in case goofy shit happens with the way the mapper sets rooms up
	for i = 1, #server.psorooms
		local room = server.psorooms[i]
		/*
			If we actually have a battle theme set, then this will initiate a blank song 
			and then change it back to the level's music once the battle ends. If the battle 
			theme is set to 'None' while another battle theme is playing, then it'll change back 
			as well.
		*/
		if battle_select[battletheme_cv.value] then
			if room.active and not room.cleared
				if room.bosswaves == 0
					if not room.musicchanged
						COM_BufInsertText(consoleplayer, "tunes battle")
						room.musicchanged = true
					end
				end
			else
				if room.musicchanged
					if not (server.questdata and server.questdata.complete) -- Makes sure the level's music doesn't play when it's supposed to play the victory theme.
						COM_BufInsertText(consoleplayer, "tunes -default")
					end
					room.musicchanged = false
				end
			end
		else
			if room.musicchanged
				COM_BufInsertText(consoleplayer, "tunes -default")
				room.musicchanged = false
			end
		end
	end
end

PSO.lib.registerFrameFunc(handleBattleMusic)