SERVER_DATA["speclock"] = {}

CreateChat "!speclock" "<id> <minutes> [reason]" (10) [[
	if args >= 2 then
		local p = tonumber(s[2])
		local mins = tonumber(s[3])
		local reason
		if args >= 3 then
			reason = string.sub(txt, pos[3])
		end
		
		if p and player(p,"exists") and mins and mins > 0 then
			SpeclockPlayer(p, mins)
			if reason then
				ServerMSG(player(id,"name").." spec. locked "..player(p,"name").." ("..mins.." mins.) for: "..reason)
			else
				ServerMSG(player(id,"name").." spec. locked "..player(p,"name").." ("..mins.." mins.)")
			end
		end
	end
]]

CreateChat "!unspeclock" "<id>" (15) [[
	local p = tonumber(s[2])
	if p and player(p,"exists") then
		if SERVER_DATA["speclock"][player(p,"ip")] then
			ServerMSG(player(id,"name").." unlocked "..player(p,"name").." from spectator")
			SpeclockPlayer(p, 0)
		end
	end
]]

function SpeclockPlayer(id,mins)
	if mins <= 0 then
		SERVER_DATA["speclock"][player(id,"ip")] = nil
	else
		SERVER_DATA["speclock"][player(id,"ip")] = mins
		parse("makespec "..id)
	end
end

addhook("minute","SpeclockUnban")
function SpeclockUnban()
	for ip, mins in pairs(SERVER_DATA["speclock"]) do
		SERVER_DATA["speclock"][ip] = SERVER_DATA["speclock"][ip] - 1
		if SERVER_DATA["speclock"][ip] <= 0 then
			SERVER_DATA["speclock"][ip] = nil
			
			local p = IPPlayer(ip)
			if p then
				ServerMSG(player(p,"name").." has been unlocked from spectator")
			end
		end
	end
end

addhook("team","SpeclockBan")
function SpeclockBan(id,team)
	if SERVER_DATA["speclock"][player(id,"ip")] then
		if team == 0 and player(id,"team") ~= 0 then
			return 0
		end
		parse("makespec "..id)
		return 1
	end
end