--GET SOUND ID function by Altiami 
--It allows to play a sound by triggering a linedef and reading its backside.

--saves time by not looking through the ENTIRE sfxinfo table every single time
local soundIdByNameCache = {}

--expects the at-most six character name AFTER sfx_ (BLua) or DS (lump)
local function getSoundIdByName(soundName)
    local soundId

    --all internal names are lowercase
    soundName = soundName:lower()

    --check if it's cached
    if soundIdByNameCache[soundName] ~= nil then
        soundId = soundIdByNameCache[soundName]
    else
        --iterate over all sounds
        for i = 0, #sfxinfo - 1 do
            if sfxinfo[i].name == soundName then
                soundId = i
                --cache the ID under the name
                soundIdByNameCache[soundName] = i
                --found the ID. Break early
                break
            end
        end
    end

    if soundId == nil then
        print(string.format("\129WARNING\128: Failed to get sound ID for\"%s\"", soundName))
        local errorNameType
        local prefix
        if soundName:sub(1, 2) == "ds" then
            errorNameType = "lump"
            prefix = "DS"
        elseif soundName:sub(1, 4) == "sfx_" then
            errorNameType = "BLua constant"
            prefix = "sfx_"
        end
        if prefix then
            print(string.format(
                "\tDid you pass a %s name and forget to remove the starting \"%s\"?",
                errorNameType,
                prefix
            ))
        end

        --failsafe a thok
        soundId = sfx_thok
    end

    return soundId
end

--VARIABLE SO YOU CAN SHUT THE ANNOUNCER UP (mostly)

local ss_shutup = CV_RegisterVar({
	name = "ss_shutup",
	defaultvalue = "Off",
	flags = 0,
	PossibleValue = CV_OnOff,
})

addHook("ThinkFrame", function()
	if leveltime ~= 1 then return end
	if not mapheaderinfo[gamemap].hasannouncer then return end

	print("Welcome to Sloppy Sludge Zone!")
	print("Use the command \x81ss_shutup \x83On\x80/\x85Off\x80 to silence the announcer or not!")
end)

local function PLAYANCR(linedef, mobj)
	--If the value of ss_shutup is Off, a sound is played according to the back of the linedef.
  if (ss_shutup.value == 0) then
	local soundStuff
	soundStuff = getSoundIdByName(linedef.backside.text)
    S_StartSound(nil, soundStuff, mobj.player)
  end
end

addHook("LinedefExecute", PLAYANCR,"PLAYANNO")
	--Call Lua function from linedef. Backside has the sound name.

	--AROUND THE WORLD - can be called from any lua
rawset(_G, "getSoundIdByName", getSoundIdByName)