-- SRB2Kart Lua Script
-- SPB Music
-- Originally written by Sal and now by James. The new version has a cvar
-- toggle, plays for spectating players, and is able to check for a music
-- lump actually being present.
-- Slightly expanded by wolfs. Includes blacklisting, randomized music,
-- and map-specific SPB music.
-- 

DynMusic.spbm = {} -- module namespace

local spbm = DynMusic.spbm -- shorthand to prevent clusterfucks

local starttime = 6*TICRATE + (3*TICRATE/4)

local  didcredit
local wantcredit
local pauselength = 3*TICRATE

local oldmapmusname -- map music to restore it
local newmapmusname -- spb music in case some outside force changes map music

local gotmusic = {} -- Honestly not sure how necessary this is.

local firstrun = 0 -- For loading spbmusic.cfg
local fucksgiven = false -- For aliasing

spbm.map_blacklist = {} -- Blacklist table

spbm.music_list = {"SPBRUN"} -- Music list. Can be expanded, but always contains at least one entry.

spbm.charmusic = {}

spbm.map_music = {} -- Table for map-specific music

local labels = {} -- Holds labels displayed when listing music, if present

local preftracknum = 1 -- Preferred track number, set by the user.

spbm.tracknum = 1 -- Actual track number, set by the script.

spbm.tracklump = nil -- This is spaghetti, but this is the track lump to use if character-specific music is defined.

spbm.cv_randomize = CV_RegisterVar({"spbrandomize", "Off", 0, CV_OnOff}) -- Randomizes which song plays during SPB rush

-- Determines how crediting is handled. "Always" shows it every time, while "Once" displays it once per map.
local cv_credit = CV_RegisterVar({"spbcredit", "Always", 0, {Never=0, Once=1, Always=2}})

-- Override cvar for map-specific SPB music. 
-- If enabled, your preferred track will always play, even on maps with specific music defined.
local cv_override = CV_RegisterVar({"spbmapoverride", "Off", 0, CV_OnOff})

-- Helper function to check blacklisted maps.
local
function BlacklistChecker()
	for k,v in ipairs(spbm.map_blacklist) do
		if (G_BuildMapName(gamemap) == v)
			return true
		end
	end
	return false
end

-- Allows disabling SPB music on specific maps
DynMusic.FuckYou("spbblacklist", function(player, map)
	if (player ~= consoleplayer) then return end
	if not (map) then
		CONS_Printf(player, "SPB Music Blacklist")
		if not (spbm.map_blacklist) then
			CONS_Printf(player, "-- Blacklist empty --")
			return
		else
			for k,v in ipairs(spbm.map_blacklist) do
				CONS_Printf(player, k..": "..v)
			end
		end
		return
	end
	for k,v in ipairs(spbm.map_blacklist) do
		if (v == map:upper()) then 
			error("specified map ("..map..") is already blacklisted") 
			return
		end
	end
	table.insert(spbm.map_blacklist, map:upper())
end)

-- Adds SPB music to the list
-- Limited error checking. Just don't be an idiot :V
DynMusic.FuckYou("addspbmusic", function(player, mus, label)	
	if (player ~= consoleplayer) then return end
	if not (mus) then
		CONS_Printf(player, "addspbmusic <lump>: Adds a music lump to the SPB music list")
		return
	end
	if (DynMusic.AddMusic(spbm.music_list, mus)) then
		CONS_Printf(player, "[SPB Music] Added track "..#spbm.music_list..": \x82"..mus:upper().."\x80")
		if (label) then
			labels[#spbm.music_list] = label
		end
	else
		error(mus.." is already in the list") 
	end
end)

DynMusic.FuckYou("addcharspbmusic", function(player, skin, lump)
	if (player ~= consoleplayer) then return end
	
	if not (skin) then
		CONS_Printf(player, "addcharspbmusic <skin> <lump>: Sets the SPB music for the given skin to the provided lump")
		return
	end
	
	if not (lump) then error("no music lump provided") return end
	
	spbm.charmusic[skin] = lump
	
	CONS_Printf(player, "[SPB Music] SPB Music for \""..skin.."\" has been set to \x82"..lump.."\x80")
end)

COM_AddCommand("delspbmusic", function(player, mus)
	if (player ~= consoleplayer) then return end
	if not (mus) then
		CONS_Printf(player, "delspbmusic <lump>: Removes a music lump from the SPB music list")
		return
	end
	for k,v in ipairs(spbm.music_list) do
		if (v == mus:upper()) then
			if (preftracknum == k) then
				preftracknum = 1 -- I'm not gonna bother accounting for a completely empty list. That's your own problem.
			end
			if (spbm.tracknum == k) then
				spbm.tracknum = 1
			end
			table.remove(spbm.music_list, k)
			if (labels[k]) then
				table.remove(labels, k)
			end
			CONS_Printf(player, "[SPB Music] Removed track: ".."\x82"..mus:upper().."\x80")
			return
		end
	end
	
	error(mus.." was not found")
end)

COM_AddCommand("delcharspbmusic", function(player, skin)
	if (player ~= consoleplayer) then return end
	
	if not (skin) then
		CONS_Printf(player, "delcharspbmusic <skin>: Removes the currently set SPB Music for the provided skin")
		return
	end
	
	spbm.charmusic[skin] = nil

	CONS_Printf(player, "[SPB Music] SPB Music for \""..skin.."\" removed")
end)

-- Lists the currently set SPB music lumps. 
-- Tells you your preferred track and if randomizer is set.
COM_AddCommand("listspbmusic", function(player)
	if (player ~= consoleplayer) then return end
	
	local str = ""
	
	CONS_Printf(player, "SPB Music List")
	
	for k,v in ipairs(spbm.music_list) do
		str = k..": "..v
		if (labels[k]) then
			str = str.." - "..labels[k]
		end
		CONS_Printf(player, str)
	end
	if (spbm.cv_randomize.value) then 
		CONS_Printf(player, "The current preferred track is \x82"..preftracknum.."\x80. Randomizer is enabled.")
	else
		CONS_Printf(player, "The current preferred track is \x82"..preftracknum.."\x80.")
	end
end)

COM_AddCommand("listcharspbmusic", function(player)
	if (player ~= consoleplayer) then return end

	local str = ""

	if not (next(spbm.charmusic)) then
		error("no character music defined")
		return
	end

	CONS_Printf("Character SPB Music List")

	for k,v in pairs(spbm.charmusic) do
		str = k..": "..v
		CONS_Printf(player, str)
	end
end)

-- Selects a song from the list for SPB rush.
DynMusic.FuckYou("setspbmusic", function(player, track)
	if (player ~= consoleplayer) then return end
	if not track then 
		CONS_Printf(player, "setspbmusic <track # or lump>: Sets the preferred SPB music to the given track")
		return
	end
	if (tonumber(track)) then -- track provided is a number
		track = tonumber(track)
		if (track > #spbm.music_list) then
			error("track number exceeds music list")
			return
		end
	else -- track is a string, find the corresponding list entry
		track = DynMusic.GetTracknumFromLump(track, spbm.music_list)
	end
	if not (track) then
		error("invalid track lump provided, resetting to default")
		preftracknum = 1
		return
	end
	preftracknum = track
	CONS_Printf(player, "SPB Music has been set to \x82"..spbm.music_list[preftracknum].."\x80.")
end)

-- Changes the default lump (SPBRUN)
-- Now you'll never be subjected to someone else's taste!
DynMusic.FuckYou("setspbdefault", function(player, lump)
	if (player ~= consoleplayer) then return end
	if not lump then 
		CONS_Printf(player, "setspbdefault <lump name>: Changes the default SPB music lump")
		return
	end
	spbm.music_list[1] = lump:upper()
	CONS_Printf(player, "Default SPB Music set to \x82"..lump.."\x80.")
end)

-- Defines SPB music for a given map
-- Does not take effect if the randomizer is enabled
-- I have no idea what the hell will happen if two songs are set to the same map
DynMusic.FuckYou("mapspbmusic", function(player, map, track)
	if (player ~= consoleplayer) then return end
	if not map and not track then
		CONS_Printf(player, "mapspbmusic <map> <track #>: Define a track number as the music for the given map")
		return
	end
	if not (track) then
		error([["]]..track..[[" is missing]])
		return
	end
	if (tonumber(track)) then -- track provided is a number
		track = tonumber(track)
		if (track > #spbm.music_list) then
			error("track number exceeds music list")
			return
		end
	else -- track is a string, find the corresponding list entry
		track = DynMusic.GetTracknumFromLump(track, spbm.music_list)
	end
	if not (track) then
		error("invalid track lump provided")
		return
	end
	spbm.map_music[map] = track
	CONS_Printf(player, "SPB Music for \x82"..map.."\x80 has been set to \x82"..spbm.music_list[track].."\x80 (".."track "..track..")")
end)

local
function SPBMusic_Queue (p, fn)
	if (spbm.cv_spbmusic.value)
	then
		if (spbm.map_blacklist and BlacklistChecker()) then return end -- don't play SPB music on blacklisted maps
		if (p.mo and p.mo.valid and spbm.charmusic[p.mo.skin]) then
			spbm.tracklump = spbm.charmusic[p.mo.skin]
		end
		if (spbm.cv_randomize.value) then
			spbm.tracknum = DynMusic.N_RandomRange(1, #spbm.music_list) -- randomizer shit
		elseif (spbm.map_music and DynMusic.MapChecker(spbm.map_music) and not (cv_override.value)) then
			spbm.tracknum = spbm.map_music[G_BuildMapName(gamemap)] -- This map uses a specific track, so set it
		else
			spbm.tracknum = preftracknum
		end
		if (gotmusic[spbm.tracknum] or gotmusic[spbm.tracklump])
		then
			if (p == consoleplayer) then
				fn(p)
			end
		else
			if (spbm.charmusic[p.mo.skin] and S_MusicExists(spbm.charmusic[p.mo.skin]:lower())) then
				if (p == consoleplayer) then
					gotmusic[spbm.tracklump] = true
					fn(p)
				end
			elseif (S_MusicExists(spbm.music_list[spbm.tracknum]:lower())) then
				if (p == consoleplayer) then
					gotmusic[spbm.tracknum] = true
					fn(p)
				end
			end
		end
	end
end

local
function SPBMusic_Change (p)
	-- map music changed by outside force, so revert to that
	if oldmapmusname == nil or (mapmusname ~= newmapmusname)
	then
		oldmapmusname = mapmusname
	end
	if (spbm.charmusic[p.mo.skin]) then
		newmapmusname = spbm.tracklump
	else
		newmapmusname = spbm.music_list[spbm.tracknum]:lower()
	end

	-- tunes means the music persists even after P_RestoreMusic
	COM_BufInsertText(p, 'tunes "' .. newmapmusname)

	if (not didcredit) and (cv_credit.value)
	then
		wantcredit = true
	end
end

local
function SPBMusic_Restore (p)
	if (mapmusname == newmapmusname)
	then
		COM_BufInsertText(p, 'tunes "' .. oldmapmusname)
	else
		P_RestoreMusic(p) -- go back to whatever
	end

	oldmapmusname = nil
	newmapmusname = nil

	if (cv_credit.value == 2) then -- spbcredit is set to "Always"
		didcredit = nil
	end
end

local
function SPBMusic_Pause (p)
	S_StopMusic(p)
	if (wantcredit)
	then
		wantcredit = nil
	end
end

local
function SPBMusic_Auto (p)
	if (p.exiting or leveltime < starttime)
	then
		return
	end

	local position = p.kartstuff[k_position]
	local spbmusic = p.spbmusic

	if (position == spbplace)
	then
		if (spbm.cv_spbmusic.value)
		then
			if (spbmusic == pauselength)
			then
				SPBMusic_Change(p)
			elseif (spbmusic >= TICRATE)
			then
				SPBMusic_Pause(p)
			end
		else
			if (spbmusic >= TICRATE)
			then
				SPBMusic_Restore(p)
			end
		end
	else
		if (spbmusic == 0 or not spbm.cv_spbmusic.value)
		then
			SPBMusic_Restore(p)
		else
			SPBMusic_Pause(p)
		end
	end
end

local
function SPBMusic_Think ()
	for p in players.iterate do
		if p.spbmusic == nil then p.spbmusic = 0 end

		if (p.exiting or leveltime < starttime)
		then
			p.spbmusic = 0
			return
		end

		local position = p.kartstuff[k_position]
		local spbmusic = p.spbmusic

		if (position == spbplace and spbmusic < pauselength)
		then
			p.spbmusic = $+1
			if (p.spbmusic == pauselength)
			then
				SPBMusic_Queue(p, SPBMusic_Change)
			elseif (p.spbmusic == TICRATE)
			then
				SPBMusic_Queue(p, SPBMusic_Pause)
			end
		elseif (position ~= spbplace and spbmusic > 0)
		then
			if (p.spbmusic == 1)
			then
				SPBMusic_Queue(p, SPBMusic_Restore)
			elseif (p.spbmusic == pauselength)
			then
				SPBMusic_Queue(p, SPBMusic_Pause)
			end
			p.spbmusic = $-1
		end

		--[[
		-- Dead players get P_RestoreMusic set on them, and so may be fucked
		if (p.playerstate == PST_REBORN and p.spbmusic ~= spbmusic)
		then
			SPBMusic_Queue(p, SPBMusic_Auto) -- Hey, it's already there!
		end
		]]
	end
end

spbm.cv_spbmusic = CV_RegisterVar(
{
	"spbmusic", "Off", -- Defaults to off. Anyone who wants it can just set it in their config.
	CV_CALL|CV_NOINIT, CV_OnOff,
	function ()
		-- Hey, are we actually playing?
		if consoleplayer ~= nil and (consoleplayer.valid)
		then
			SPBMusic_Queue(consoleplayer, SPBMusic_Auto)
		end
	end
})

addHook ("ThinkFrame", SPBMusic_Think)

addHook ("MapLoad", function ()
	didcredit = nil
end)

hud.add (function (_,p)
	if (wantcredit)
	then
		S_ShowMusicCredit(consoleplayer)
		didcredit  = true
		wantcredit = nil
	end
end)
