-- Helper functions for Dynamic Music
-- Includes Pseudorandom Numbers Library v1.0, by LJ Sonic


-- THIS LUMP IS THE CLOSEST YOU'LL GET TO THE CODE VERSION OF THE ANTICHRIST --


rawset(_G, "DynMusic", {}) -- Global DynMusic table


-- RNG Functions --


local t, x, y, z, w = 0, 6278, 975, 39207, 45678

DynMusic.N_Random = function()
    t = x ^^ (x << 11)
    x, y, z, w = y, z, w, w ^^ (w >> 19) ^^ t ^^ (t >> 8)
    return w
end

DynMusic.N_RandomKey = function(n) return abs(DynMusic.N_Random() % n) end
DynMusic.N_RandomRange = function(a, b) return a + abs(DynMusic.N_Random() % (b - a + 1)) end


-- Dynamic Music Common Functions --

local fucksgiven -- Don't ask.

-- Alias to command table
DynMusic.fuckstogive = {}

-- Function for checking music on a specific map
DynMusic.MapChecker = function(tbl)
	for k,v in pairs(tbl) do -- pairs because ipairs hates string keys
		if (G_BuildMapName(gamemap) == k)
			return true
		end
	end
	return false
end

-- Generic function to add music to a list
-- The "map" param is optional, it maps the string provided to a level as a key.
-- If "fuck" is 1, the table is two dimensional. Only to be used with the My Music module.
-- This function is a piece of shit. I know.
DynMusic.AddMusic = function(list, lump, map, fuck)
	lump = lump:upper() -- fuck you this saves time
	if (fuck == 1) then -- Do this shit first. This is the My Music logic
		if not (map) then
			return false -- No point in using this without supplying a map, dipshit.
		end
		
		-- If we've made it here, assume we have everything necessary.
		if not (list[map]) then
			list[map] = {} -- Not sure how necessary this is.
		end
		
		for k,v in ipairs(list[map]) do
			if (v == lump) then 
				return false -- lump is already in the list
			end
		end
		
		table.insert(list[map], lump)
		return true -- lump was added
	elseif (fuck == 2) then 
		if not (map) then return false end
		
		if (list[map] == lump) then
			return false -- YOU ALREADY ADDED THIS YA FUCKIN IDIOT
		else -- success, you're not an idiot
			list[map] = lump
			return true
		end
	end
	
	if not (map) then
		for k,v in ipairs(list) do
			if (v == lump) then 
				return false -- lump is already in the list
			end
		end
		
		table.insert(list, lump)
		return true -- lump was added
	else -- map was provided, add the song to the list using that as the key
		list[map] = lump
		return true
	end
end

DynMusic.GetTracknumFromLump = function(track, list)
	for k,v in ipairs(list) do
		if (track:upper() == v) then
			return k -- return the key, it's the value we want
		end
	end
	return 0 -- we found nothing
end

-- Sound replacement function, used for custom global alarms
-- Written by Namolos
DynMusic.replaceSoundByMobj = function(mobj, oldsound, newsound)
    if (S_SoundPlaying(mobj, oldsound))
        S_StopSoundByID(mobj, oldsound)
        S_StartSound(mobj, newsound)
    end
end

-- I hate the fact that this function needs to exist
DynMusic.GetMyDamnShit = function (wtf)
	local shit = {}
	for s in wtf:gmatch("[^\x7F]+")
	do
		table.insert(shit, s)
	end
	return unpack(shit)
end

-- this is even worse than the last one dear god
DynMusic.FuckMe = function (name, fn)
	CV_RegisterVar({
		name, "",
		CV_CALL|CV_NOINIT, nil,
		function (cv)
			local s = cv.string
			if (s ~= "")
			then
				fn(consoleplayer, DynMusic.GetMyDamnShit(s))
				COM_BufInsertText(consoleplayer, cv.name ..' ""')
			end
		end
	})
end

-- Just use like COM_AddCommand
DynMusic.FuckYou = function (name, ...)
	local dummyname = "_" .. name
	DynMusic.fuckstogive[name] = dummyname
	DynMusic.FuckMe(dummyname, ...)
end

addHook ("ThinkFrame", function ()
	-- Register aliases to dummy commands because Lua commands get sent over the
	-- network as TEXTCMD. And that means you'll get NetXCmd full if you send
	-- too many. And that could very likely happen with config loading.
	if consoleplayer then
		if (not fucksgiven) then
			for name, dummyname in pairs (DynMusic.fuckstogive)
			do
				-- wait 2 because first run of command ticker
				-- counts it down before checking.
				-- fucking kill me already - wolfs
				COM_BufInsertText(consoleplayer, string.format(
				'alias %s %s "'..
				'$1\x7F$2\x7F$3\x7F'..
				'$4\x7F$5\x7F$6\x7F'..
				'$7\x7F$8\x7F$9\x7F', name, dummyname))
			end
			COM_BufInsertText(consoleplayer, "exec dynmusic.cfg -noerror") -- might as well load global config here
			fucksgiven = true
		end
	end
end)
