-- desert bus stuff

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

local function ReduceBrightness()
	server.totalbrightness = $ or 255
	if leveltime % 1024 == 0 then
		server.totalbrightness = 255
	end
	if leveltime % 6 == 0 and leveltime % 1024 <= 500 and leveltime % 1024 > 32 then
		server.totalbrightness = $ - 2
	end
	if leveltime % 6 == 0 and server.totalbrightness ~= 255 and (leveltime % 1024 >= 672 or leveltime % 1024 <= 32) then
		server.totalbrightness = $ + 3
	end
	for i = 0, #sectors do
		local s = sectors[i]
		if not s continue end
		s.lightlevel = server.totalbrightness
	end
end

local function EXTtoINT(i)
	local dummy = "mudmudmud"
	if i.len(i) != 2 then return end // Do we have an extended map ID without the MAP bit?
	if tonumber(i) != nil and tonumber(i) < 100 then return i end // If the ID is a number... why? Return itself.
	i = tostring(i:lower())
	local x, y, p, q
	local ttable = {}
	for k, v in dummy.gmatch(i, "%w") do
		table.insert(ttable, k)
	end
	x, y = ttable[1], ttable[2]
	if tonumber(x) != nil then return end // Is our first character a number?!
	p = dummy.byte(x)-97
	if tonumber(y) != nil then q = y
	else q = dummy.byte(y)-87 end
	return ((36*p+q)+100)
end

addHook("ThinkFrame", function()
	if mapheaderinfo[gamemap].desertbus then
		ReduceBrightness()
		for p in players.iterate do
			if p.deadtimer > 0 then
				p.starpostnum = 0
			end
			if not (p.mo and p.mo.valid) then continue end
			-- wind stuff because fuck wind sectors
			if leveltime > STARTTIME + 1*TICRATE and p.kartstuff[k_respawn] <= 0 and P_IsObjectOnGround(p.mo) then
				P_Thrust(p.mo, 0, FRACUNIT/24)
			end
		end
	end
end)

addHook("MusicChange", function(oldname, newname)
	if mapheaderinfo[gamemap].desertbus and (snowydesert.value == 1 or snowydesert.value == 3 or encoremode) then
		if leveltime < STARTTIME then -- hack
			return "ESTART"
		end
	end
end)

freeslot("SPR_MSCA", "SPR_MSCB")

-- cacti stuff
addHook("MobjSpawn",function(mo)
	if not mapheaderinfo[gamemap].desertbus then return end
	if (snowydesert.value == 1 or snowydesert.value == 3 or encoremode) then
		if mo.valid then
			mo.sprite = SPR_XMS3
			mo.frame = A
		end
	else
		if mo.valid then
			mo.sprite = SPR_MSCB
			mo.frame = A
		end
	end
end, MT_CACTI2)

addHook("MobjSpawn",function(mo)
	if not mapheaderinfo[gamemap].desertbus then return end
	if (snowydesert.value == 1 or snowydesert.value == 3 or encoremode) then
		if mo.valid then
			mo.state = S_SMK_SNOWBALL
		end
	else
		if mo.valid then
			mo.sprite = SPR_MSCA
			mo.frame = A
		end
	end
end, MT_CACTI1)