-- Colorful Rollout Knockout

local rk_color = {
	active = false,
	activelock = false,
	selected_cs = nil,
	cd_downset = 70,
	cd_down = 70,
	cd_up = 140,
	cd_select = 140,
	time_up = 35,
	colorsectors = {[0] = 41,[1] = 42,[2] = 43,[3] = 44,[4] = 45,[5] = 46,[6] = 47}
}

addHook("MapLoad", do
	if rk_color.activelock == false
		rk_color.active = false
	else
		rk_color.activelock = false
	end
	rk_color.selected_cs = nil
	rk_color.cd_downset = 105
	rk_color.cd_down = 70
	rk_color.cd_up = 140
	rk_color.cd_select = 140
	rk_color.time_up = 35
end)

addHook("LinedefExecute", do rk_color.active = true rk_color.activelock = true end, "RK_COLOR")

addHook("ThinkFrame", do
	if rk_color.active == true
		
		if leveltime == 5
			for sector in sectors.iterate do
				if sector.tag >= 1 and sector.tag <= 9
					sector.floorheight = 512*FRACUNIT
				end
			end
		end
		if rk_color.cd_downset < 35 then rk_color.cd_downset = 105 end
		if rk_color.selected_cs == nil
			if rk_color.cd_select != 0
				rk_color.cd_select = $ - 1
			else
				rk_color.selected_cs = P_RandomRange(1,6) 
				local num = rk_color.colorsectors[rk_color.selected_cs]
				sectors[num].ceilingheight = 1600*FRACUNIT
				sectors[41].ceilingheight = 896*FRACUNIT
				S_StartSound(nil, sfx_alarm, consoleplayer)
				rk_color.cd_select = 105
			end
		elseif rk_color.selected_cs != nil
			if rk_color.cd_down != 0
				if rk_color.cd_down == 1
					S_StartSound(nil, sfx_doora1, consoleplayer)
				end
				rk_color.cd_down = $ - 1
			else
				if rk_color.cd_up != 0
					rk_color.cd_up = $ - 1
					for sector in sectors.iterate do
						if sector.tag >= 1 and sector.tag <= 9
							if sector.tag != rk_color.selected_cs
								if sector.floorheight >= 0
									sector.floorheight = $ - FRACUNIT*64
								end
							end
						end
					end
				else
					local num = rk_color.colorsectors[rk_color.selected_cs]
					sectors[num].ceilingheight = 896*FRACUNIT
					sectors[41].ceilingheight = 1600*FRACUNIT
					if rk_color.time_up != 0
						if rk_color.time_up == 34
							S_StartSound(nil, sfx_doord2, consoleplayer)
						end
						for sector in sectors.iterate do
							if sector.tag >= 1 and sector.tag <= 9
								if sector.tag != rk_color.selected_cs
									if sector.floorheight < 512*FRACUNIT
										sector.floorheight = $ + FRACUNIT*64
									else
										sector.floorheight = 512*FRACUNIT
									end
								end
							end
						end
						rk_color.time_up = $ - 1
					else
						rk_color.cd_up = 140
						if rk_color.cd_downset > 15
							rk_color.cd_downset = $ - 3
						end
						rk_color.cd_down = rk_color.cd_downset
						rk_color.time_up = 35
						rk_color.selected_cs = nil
					end
				end
			end
		end
	end
end)

addHook("NetVars", function(net)
	rk_color = net($)
end)