local ThisServerName = _GetConVar_String("hostname")
local ThisServerIP = _GetConVar_String("ip")
local IPTranslate = {}
IPTranslate["208.122.49.117"] = "ZS Server"
IPTranslate["208.122.49.118"] = "SandBox Server"
IPTranslate["208.122.49.119"] = "NoX 2 CTF Server"
IPTranslate["208.122.49.121"] = "NoX 2 Arena Server"
IPTranslate["208.122.49.122"] = "Buggy Racer Server"
IPTranslate["208.122.49.116"] = "GMod9"

local PreDeleteQueue = {}
local DeleteQueue = {}
local ReadAlready = {}

local CSCSpam = {}

function CrossServerChat(sender, text)
	CSCSpam[sender] = CSCSpam[sender] or _CurTime()

	if CSCSpam[sender] > _CurTime() then _PrintMessage(sender, 3, "Limit CSC messages to 1 per 5 seconds.") return end

	if string.len(text) <= 0 then _PrintMessage(sender, 3, "That message is too short.") return end

	text = string.gsub(text, "~", ".")

	CSCSpam[sender] = _CurTime() + 5

	local id = 1
	while _file.Exists("C:/srcds/garrysmod/data/crossserverchat/"..id..".txt") do
		id = id + 1
	end

	_file.Write("C:/srcds/garrysmod/data/crossserverchat/"..id..".txt", ThisServerIP.."~".._CurTime().."~".._PlayerInfo(sender, "name")..": "..text)
	PreDeleteQueue[id..".txt"] = true

	_PrintMessage(sender, 3, "Sent CSC request.")
end

local function CSCGetMessages()
	for _, filename in _file.Find("C:/srcds/garrysmod/data/crossserverchat/*.txt") do
		local filecontents = _file.Read("C:/srcds/garrysmod/data/crossserverchat/"..filename)

		if ReadAlready[filecontents] then
			ReadAlready[filecontents] = nil
		else
			local contents = explode(filecontents, "~")

			local fromIP = contents[1]
			local fromServer = IPTranslate[fromIP] or fromIP
			local message = contents[3]

			_PrintMessageAll(3, "(CSC from " .. fromServer .. ") " .. message)

			ReadAlready[filecontents] = true
		end

		if PreDeleteQueue[filename] then
			DeleteQueue[filename] = true
			PreDeleteQueue[filename] = nil
		elseif DeleteQueue[filename] then
			_file.Delete("C:/srcds/garrysmod/data/crossserverchat/"..filename)
			DeleteQueue[filename] = nil
		end
	end
end
AddTimer(5, 0, CSCGetMessages)

for _, filename in _file.Find("C:/srcds/garrysmod/data/crossserverchat/*.txt") do
	local filecontents = _file.Read("C:/srcds/garrysmod/data/crossserverchat/"..filename)
	local contents = explode(filecontents, "~")

	if contents[1] == ThisServerIP then
		_file.Delete("C:/srcds/garrysmod/data/crossserverchat/"..filename)
	end
end
