-- My Music, by wolfs
-- Includes Encore Music, by SteelT, for convenience
-- This is a compendium of some of the shittiest code I've ever written. Don't be expecting quality here.

DynMusic.mmus = {} -- Table for My Music module vars

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

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

mmus.music_list = {}

mmus.encoremusic = {}

local labels = {}

local encorelabels = {}

local rand, rand2, musname, mapname

mmus.map_music = {} -- used with mmus.music_list, helps keep things clean

mmus.defaults = {} -- Map music defaults

mmus.votemusic = {} -- Stores additional voting music

mmus.queue = {}

mmus.queuesong = nil

mmus.tracklump = nil

mmus.randomized = false

mmus.voterandomized = false

mmus.queued = false

mmus.cv_mymusic = CV_RegisterVar({"mymusic", "Off", 0, CV_OnOff})

mmus.cv_encoremusic = CV_RegisterVar({"encoremusic", "Off", 0, CV_OnOff})

-- Copy of "addspbmusic"
-- Adds a song to the additional song table for a map
DynMusic.FuckYou("addmapmusic", function(player, map, mus, label)
	if (player ~= consoleplayer) then return end

	if not (map) then
		CONS_Printf(player, "addmapmusic <map> <lump>: Adds a music lump for the given map")
		return
	end
	
	map = map:upper()
	
	if not (mus) then
		error("no lump provided")
		return
	end

	if (DynMusic.AddMusic(mmus.music_list, mus, map, 1)) then
		CONS_Printf(player, "[My Music] Added track for "..map..": \x82"..mus:upper().."\x80")

		if (label) then
			if not (labels[map]) then
				labels[map] = {}
			end
			table.insert(labels[map], label)
		end
	else
		error(mus.." is already in the list for this map") 
	end
end)

-- Adds a encore music for a specific map
DynMusic.FuckYou("addencoremusic", function(p, map, muslump, label)
	if (p ~= consoleplayer) then return end
	local mapstr
	local muslumpstr

	if not (map) and not (muslump) then
		CONS_Printf(p, "addencoremusic <map> <muslump>: Adds a encore music lump for the specified map.")
		return
	end

	if not (muslump) then
		error("No music lump was provided")
		return
	end

	mapstr = map:upper()

	if mapstr:find("MAP") == nil then
		mapstr = "MAP"..$ -- prepend "MAP" to start of mapstr
	end

	muslumpstr = muslump:gsub("O_", "", 1) -- Remove O_ prefix
	mmus.encoremusic[mapstr] = muslumpstr

	if (label)
		encorelabels[mapstr] = label
	end

	CONS_Printf(p, "[Encore Music] Encore music for \x82"..mapstr.."\x80 has been set to track \x82"..muslumpstr.."\x80.")
end)

-- Command for changing default map music
-- Used to get around custom levels going over your music wad and replacing your choices
-- Label functionality removed here, because fuck you.
DynMusic.FuckYou("setdefaultmapmusic", function(player, map, mus)
	if (player ~= consoleplayer) then return end
	
	if not (map) then
		CONS_Printf(player, "setdefaultmapmusic <map> <lump>: Changes the default music choice for the given map")
		return
	end
	
	map = map:upper()
	
	if not (mus) then
		error("no lump provided")
		return
	end
	
	if (DynMusic.AddMusic(mmus.defaults, mus, map, 2)) then
		CONS_Printf(player, "[My Music] Changed default track for "..map..": \x82"..mus:upper().."\x80")
	else
		error(mus.." is already the default track for this map") 
	end
end)

DynMusic.FuckYou("overrideintermission", function(player, mus)
	if (player ~= consoleplayer) then return end

	if not (mus) then
		CONS_Printf(player, "overrideintermission <lump>: Overrides the intermission music used. This is only heard while spectating.")
		
		if (mmus.intermissionoverride) then
			CONS_Printf(player, "The current intermission music override is: \x82"..mmus.intermissionoverride.."\x80")
		end
		
		return
	end

	-- Just set it flat out so it can be modified at runtime. No error checking because fuck you.
	mmus.intermissionoverride = mus
	CONS_Printf(player, "[My Music] Added intermission music override: \x82"..mmus.intermissionoverride:upper().."\x80")
end)

DynMusic.FuckYou("addvotemusic", function(player, vote, voteea, voteeb)
	if (player ~= consoleplayer) then return end

	local votemus = nil

	if not (vote) then
		CONS_Printf(player, "addvotemusic <vote lump> <voteea lump> <voteeb lump>: Adds voting music to randomize between. Use the same lump for all three arguments to ignore VOTEEA and VOTEEB lumps")
		return
	end

	if not (voteea) or not (voteeb) then
		error("too few parameters")
		return
	end

	votemus = {vote, voteea, voteeb}
	table.insert(mmus.votemusic, votemus)
	CONS_Printf(player, "[My Music] Added vote music: \x82"..table.concat(votemus, ", "):upper().."\x80")
end)

DynMusic.FuckYou("setdefaultvotemusic", function(player, vote, voteea, voteeb)
	if (player ~= consoleplayer) then return end

	if not (vote) then
		CONS_Printf(player, "setdefaultvotemusic <vote lump> <voteea lump> <voteeb lump>: Changes the default voting music used.")

		if (mmus.votedefault) then
			CONS_Printf(player, "The current default vote music is: \x82"..table.concat(mmus.votedefault, ", ").."\x80")
		end

		return
	end

	if not (voteea) or not (voteeb) then
		error("too few parameters")
		return
	end

	-- Just set it flat out so it can be modified at runtime. No error checking because fuck you.
	mmus.votedefault = {vote, voteea, voteeb}
	CONS_Printf(player, "[My Music] Changed default vote music: \x82"..table.concat(mmus.votedefault, ", "):upper().."\x80")
end)

COM_AddCommand("delmapmusic", function(player, map, mus)
	if (player ~= consoleplayer) then return end

	if not (map) then
		CONS_Printf(player, "delmapmusic <map> <lump>: Removes a music lump from the given map")
		return
	end
	
	map = map:upper()
	
	if not (mus) then
		error("no lump provided")
		return
	end

	for k,v in ipairs(mmus.music_list[map]) do

		if (v == mus:upper()) then
			table.remove(mmus.music_list[map], k)

			if (labels[map][k]) then
				table.remove(labels[map], k)
			end

			CONS_Printf(player, "[My Music] Removed track for "..map..": \x82"..mus:upper().."\x80")
			return
		end
	end
	
	error(mus.." was not found") 
end)

COM_AddCommand("delencoremusic", function(p, map)
	if (p ~= consoleplayer) then return end
	local mapstr

	if not (map) then
		CONS_Printf(p, "delencoremusic <map>: Removes a encore music for the specified map.")
		return
	end

	mapstr = map:upper()

	if mapstr:find("MAP") == nil then
		mapstr = "MAP"..$ -- prepend "MAP" to start of mapstr
	end

	if (mmus.encoremusic[mapstr] == nil) then
		error("Encore music for "..mapstr.." does not exist")
		return
	end

	mmus.encoremusic[mapstr] = nil

	if (label) then
		encorelabels[mapstr] = nil
	end

	CONS_Printf(p, "[Encore Music] Encore music for \x82"..mapstr.."\x80 was removed.")
end)

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

	if not (map) then
		CONS_Printf(player, "delmapdefault <map>: Deletes custom default music for the given map")
		return
	end
	
	map = map:upper()
	
	if not (mmus.defaults[map]) then
		error(map.." has no custom default to delete")
		return
	end
	
	mmus.defaults[map] = nil
	CONS_Printf(player, "[My Music] Default for \x82"..map.."\x80 deleted.")
end)

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

	if not (key) then
		CONS_Printf(player, "delvotemusic <key>: Deletes a vote music entry from the list. Use \"listvotemusic\" to view the list")
		return
	end

	if not (mmus.votemusic[key]) then
		error("invalid key specified")
		return
	end

	table.remove(mmus.votemusic, key)
	CONS_Printf(player, "[My Music] Deleted vote music entry at key \x82"..key.."\x80.")
end)

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

	mmus.intermissionoverride = nil
	CONS_Printf(player, "[My Music] Intermission music override deleted.")
end)

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

	mmus.votedefault = nil
	CONS_Printf(player, "[My Music] Custom vote music default deleted.")
end)

-- Copy of "listspbmusic"
-- Lists additional music defined for the specified map
COM_AddCommand("listmapmusic", function(player, map)
	if (player ~= consoleplayer) then return end
	local str = ""

	if not (map) then
		CONS_Printf(player, "listmapmusic <map>: Lists additional music defined for the given map")
		return
	end
	
	map = map:upper()
	
	if not (mmus.music_list[map]) then
		error("no music defined for "..map)
		return
	end

	CONS_Printf(player, map.." Additional Music List")

	for k,v in ipairs(mmus.music_list[map]) do
		str = k..": "..v

		if (labels[map][k]) then
			str = str.." - "..labels[map][k]
		end

		CONS_Printf(player, str)
	end
end)

COM_AddCommand("listencoremusic", function(p)
	if (p ~= consoleplayer) then return end
	local str = ""

	if (next(mmus.encoremusic) == nil) then
		CONS_Printf(p, "Encore music table is empty")
		return
	end

	CONS_Printf(p, "Encore Music List")

	for k,v in pairs(mmus.encoremusic) do
		str = k..": "..v

		if (encorelabels[k]) then
			str = str.." - "..encorelabels[k]
		end

		CONS_Printf(p, str)
	end
end)

COM_AddCommand("listmapdefaults", function(player)
	if (player ~= consoleplayer) then return end
	local str = ""
	
	if not (next(mmus.defaults)) then
		error("no custom defaults defined")
		return
	end

	CONS_Printf(player, "Default Map Music List")

	for k,v in pairs(mmus.defaults) do -- ipairs hates string keys
		str = k..": "..v
		CONS_Printf(player, str)
	end
end)

COM_AddCommand("listvotemusic", function(player)
	if (player ~= consoleplayer) then return end
	local str = ""

	if not (next(mmus.votemusic)) then
		error("no custom vote music defined")
		return
	end

	CONS_Printf(player, "Vote Music List")

	for k,v in ipairs(mmus.votemusic) do
		str = k..": "..v
		CONS_Printf(player, str)
	end
end)

COM_AddCommand("queue", function(player, ...)
	if (player ~= consoleplayer) then return end
	
	if not (...) then 
		CONS_Printf(player, "queue <lump>: Determines which song will play next. Can be used with multiple songs to create playlists")
		return
	end
	
	mmus.queue = {...}
	CONS_Printf(player, "[My Music] Queued \x82"..table.concat({...}, ", ").."\x80 to play.")
end)

COM_AddCommand("listqueue", function(player)
	if (player ~= consoleplayer) then return end
	
	CONS_Printf(player, "Current song queue")

	if (mmus.queue ~= nil) then

		if not (#mmus.queue) then
			CONS_Printf(player, "Queue is empty")
			return
		end

		for k,v in ipairs(mmus.queue) do
			CONS_Printf(player, k..": "..v)
		end
	else
		error("queue undefined")
	end
end)

COM_AddCommand("clearqueue", function(player)
	if (player ~= consoleplayer) then return end
	
	mmus.queue = {}
	CONS_Printf(player, "[My Music] Queue cleared")
end)

-- PRIORITY LIST:
-- 1. Queue
-- 2. Encore Music
-- 3. My Music/Music overrides

addHook("MusicChange", function(oldmusic, newmusic, flags, looping)

	--print("Music change from "..oldmusic.." to "..newmusic)

	-- Shorthand for readability
	musname = mapheaderinfo[gamemap].musname
	mapname = G_BuildMapName(gamemap)

	-- Check if the next song is the map's default
	if (newmusic == musname) then

		-- Queue handling (works independently from rest of the module)
		if (mmus.queue and #mmus.queue) or (mmus.queuesong) then

			if not (mmus.queued) then
				mmus.queuesong = mmus.queue[1]
				table.remove(mmus.queue, 1)

				CONS_Printf(consoleplayer, "[My Music] Playing queued song: \x82"..mmus.queuesong.."\x80")

				if not (mmus.queue[1]) then
					CONS_Printf(consoleplayer, "[My Music] Reached the end of the queue")
				end

				mmus.queued = true
			end

			return mmus.queuesong, flags, true
		end

		-- Encore music handling
		if (encoremode and mmus.cv_encoremusic.value) then
			if (mmus.encoremusic and DynMusic.MapChecker(mmus.encoremusic)) then
				--print("Playing the encore music for "..mapname.." ("..mmus.encoremusic[mapname]..")")
				return mmus.encoremusic[mapname], flags, true
			end
		end
	end

	if (mmus.cv_mymusic.value) then

		-- Handle overrides first
		if (mmus.intermissionoverride) then
			if (newmusic == "racent") then
				return mmus.intermissionoverride:upper(), flags, true
			end
		end

		if (next(mmus.votemusic)) or (mmus.votedefault) then

			-- Handle randomization shit
			if (next(mmus.votemusic)) then 

				if not (mmus.voterandomized) then
					rand2 = DynMusic.N_RandomRange(0, #mmus.votemusic)
					mmus.voterandomized = true
				end

				if (rand2 ~= 0) then -- I actually fucking hate this.
					if (newmusic == "vote") then
						return mmus.votemusic[rand2][1], flags, true
					elseif (newmusic == "voteea") then
						return mmus.votemusic[rand2][2], flags, true
					elseif (newmusic == "voteeb") then
						return mmus.votemusic[rand2][3], flags, true
					end
				else
					if (mmus.votedefault) then
						if (newmusic == "vote") then
							return mmus.votedefault[1], flags, true
						elseif (newmusic == "voteea") then
							return mmus.votedefault[2], flags, true
						elseif (newmusic == "voteeb") then
							return mmus.votedefault[3], flags, true
						end
					else
						return -- fall back to existing vote lumps
					end
				end

			end

			if (mmus.votedefault) then
				-- The fact that this exact block is used twice hurts my brain.
				if (newmusic == "vote") then
					return mmus.votedefault[1], flags, true
				elseif (newmusic == "voteea") then
					return mmus.votedefault[2], flags, true
				elseif (newmusic == "voteeb") then
					return mmus.votedefault[3], flags, true
				end
			end
		end

		if (newmusic == musname) then

			if (mmus.music_list[mapname]) then
				mmus.map_music = mmus.music_list[mapname]

				if not (mmus.randomized) then
					rand = DynMusic.N_RandomRange(0, #mmus.map_music)
					mmus.randomized = true
				end

				if (rand ~= 0) then
					mmus.tracklump = mmus.map_music[rand]
					return mmus.tracklump, flags, true
				else -- use the default music lump
					if (mmus.defaults[mapname]) then -- custom default is set, so use that
						mmus.tracklump = mmus.defaults[mapname]
						return mmus.tracklump, flags, true
					else
						mmus.tracklump = nil -- reset tracklump for unmodified music track
						return
					end
				end
			else -- WHOOPS, DUPLICATE THIS DUMB SHIT OR THE REPLACEMENT FUNCTIONALITY DOESN'T WORK UNLESS YOU HAVE MULTIPLE SONGS DEFINED
				if (mmus.defaults[mapname]) then
					mmus.tracklump = mmus.defaults[mapname]
					return mmus.tracklump, flags, true
				end
			end
		end
	end
end)

addHook("MapChange", function(mapnum)
	mmus.randomized = false
	mmus.voterandomized = false
	mmus.queued = false
	mmus.queuesong = nil
end)
