-- Final Lap Music by Snu (This took too long)

DynMusic.flm = {}	-- module namespace
local flm = DynMusic.flm	-- shorthand to prevent clusterfucks
flm.cv_flmusic = CV_RegisterVar({"finallapmusic", "Off", 0, CV_OnOff})

flm.list = {} -- all our final lap music goes in here

addHook("MapLoad", function()
	for p in players.iterate
		-- reset final lap music related vars
		p.flm_mod, p.flm_t, p.flm_c = nil, nil, nil
	end
end)

-- function to trigger final lap music for mods that want to
flm.TriggerFLM = function(timer)
	timer = $ and max(1, min(73, $)) or 1
	
	local p = displayplayers[0]
	p.flm_mod = true	-- this is important
	p.flm_c = nil	-- remove this to retrigger it
	p.flm_t = timer	-- set timer
end

DynMusic.FuckYou("addflmusic", function(p, lump, flmlump)
	if (p ~= consoleplayer) then return end
	if not (lump) then CONS_Printf(p, "addflmusic <lump> <flmlump>: Adds final lap music for a music lump.") return end
	if not (flmlump) then CONS_Printf(p, "\x82".."[Final Lap Music] ".."\x83".."NOTICE:".."\x80".." No final lap music lump provided.") return end
	
	lump, flmlump = lump:upper(), flmlump:upper()	-- uppercase the music lumps
	-- global flmusic
	if (lump == "GLOBALMUSIC")
		if (flm.list[6969696]) then CONS_Printf(p, "\x82".."[Final Lap Music] ".."\x83".."NOTICE:".."\x80".." Global final lap music already exists: ".."\x82"..flm.list[6969696]) end
		CONS_Printf(p, "\x82".."[Final Lap Music] ".."\x80"..(flm.list[6969696] and "Replaced" or "Added").." global final lap music: ".."\x82"..flmlump)
		flm.list[6969696] = flmlump	-- music lumps cant be more than 6 characters so there's no way this can overwrite something... right?
		return
	end
	
	-- truncate lump names if they're too long
	if (lump:len() > 6)
		CONS_Printf(p, "\x82".."[Final Lap Music] ".."\x83".."NOTICE:".."\x80".." Music name too long - truncated to six characters.")
		lump = lump:sub(1, 6)
	end
	if (flmlump:len() > 6)
		CONS_Printf(p, "\x82".."[Final Lap Music] ".."\x83".."NOTICE:".."\x80".." Music name too long - truncated to six characters.")
		lump = flmlump:sub(1, 6)
	end
	
	if (flm.list[lump]) then CONS_Printf(p, "\x82".."[Final Lap Music] ".."\x83".."NOTICE:".."\x80".." Final lap music for "..lump.." already exists: ".."\x82"..flm.list[lump]) end
	CONS_Printf(p, "\x82".."[Final Lap Music] ".."\x80"..(flm.list[lump] and "Replaced" or "Added").." final lap music for "..lump..": ".."\x82"..flmlump)
	flm.list[lump] = flmlump
end)

COM_AddCommand("delflmusic", function(p, lump)
	if (p ~= consoleplayer) then return end
	if not (lump) then CONS_Printf(p, "delflmusic <lump>: Deletes final lap music from a music lump.") return end
	
	lump = lump:upper()	-- uppercase the music lump
	
	-- global flmusic check
	if (lump == "GLOBALMUSIC")
		CONS_Printf(p, "\x82".."[Final Lap Music] ".."\x80".."Removed global final lap music.")
		flm.list[6969696] = nil
		return
	end
	
	-- truncate lump name if it's too long
	if (lump:len() > 6)
		CONS_Printf(p, "\x82".."[Final Lap Music] ".."\x83".."NOTICE:".."\x80".." Music name too long - truncated to six characters.")
		lump = lump:sub(1, 6)
	end
	
	CONS_Printf(p, "\x82".."[Final Lap Music] ".."\x80".."Removed final lap music from "..lump".")
	flm.list[lump] = nil
end)

-- Clears final lap music from all maps
COM_AddCommand("clearflmusic", function(p)
	if (p ~= consoleplayer) then return end
	
	CONS_Printf(p, "\x82".."[Final Lap Music]".."\x80".." Cleared all final lap music.")
	flm.list = {}
end)

COM_AddCommand("listflmusic", function(p)
	if (p ~= consoleplayer) then return end
	
	if (next(flm.list) == nil) then
		CONS_Printf(p, "\x82".."[Final Lap Music]".."\x80".." No final lap music defined.")
		return
	end
	
	CONS_Printf(p, "\x82".."[Final Lap Music]".."\x80".." Final lap music list:")
	for k, v in pairs(flm.list)
		if (k == 6969696) then continue end -- we'll always print this last
		CONS_Printf(p, k..": ".."\x82"..v)
	end
	if flm.list[6969696] then CONS_Printf(p, "Global FLMusic: ".."\x82"..flm.list[6969696]) end
end)

-- sadly I cant just use MusicChange for this... the chad of all hooks...
local flm_music
addHook("ThinkFrame", do
	local p = displayplayers[0]
	for cp in displayplayers.iterate do	-- have I mentioned how much I love this
		if (((cp.laps+1) == numlaps) and (numlaps > 1) and flm.cv_flmusic.value) -- main trigger, final lap (with flmusic enabled)
		or (p.flm_mod)	-- custom mod trigger
			if (p.flm_c) then return end	-- music already triggered, stop functions
			
			-- get music here instead of later on
			-- S_MusicName() will technically return something else while we transition
			if flm.list[S_MusicName()]
				flm_music = flm.list[S_MusicName()]
			else
				-- cant find lump specific flmusic so check for global
				if flm.list[6969696]
					flm_music = flm.list[6969696]
				end
			end
			
			if (flm_music) -- we need to have music
			and not (cp.spbmusic or cp.kartstuff[k_invincibilitytimer] or (cp.kartstuff[k_growshrinktimer] > 0)) -- checks for spbmusic, invincibility and growth
			and not (cp.mo and cp.mo.tsr_ultimateon)	-- tsr plug
				local flm_tune = (p.flm_t == 73) and flm_music or "-none"	-- what we'll be setting it to
				
				COM_BufInsertText(p, "tunes "..flm_tune)
				if (p.flm_t == 73)	-- 73 is when the music SHOULD trigger
					flm_music = nil	-- reset the tune here
					p.flm_mod = nil	-- reset this, just for convenience
					p.flm_c = true	-- make sure nothing else happens
					S_ShowMusicCredit()
				end
			end
			-- increase timer when active
			p.flm_t = $ and min(73, p.flm_t+1) or 1
		else
			-- reset flm_music here for weird cases (joining another server, map change, etc)
			flm_music = nil
		end
	end
end)