CHAT_CMD = {}
CHAT_ATTACHMENT = {}

SERVER_DATA["disabled_cmd"] = SERVER_DATA["disabled_cmd"] or {}

addhook("say","AM.Say")
function AM.Say(id,txt)
	if string.sub(txt, -2) == "@C" then
		txt = string.sub(txt, 1, -3)
	end

	local ret
	if string.sub(txt, 1, 1) == "!" or string.sub(txt, 1, 1) == "@" then
		local s, sp = txt:split()
		local command_name = s[1]
		local command_table = CHAT_CMD[command_name]
		if command_table then
			if not SERVER_DATA["disabled_cmd"][command_name] then
				if SERVER_RANK[USER[id]["rank"]].lvl >= command_table.lvl then
					ProtectedCall(command_table.f, id, txt, s, sp, #s)
				else
					ErrorMSG(id, "You haven't got enough rights for this command")
				end
			else
				ErrorMSG(id, "This command has been disabled")
			end
		else
			ErrorMSG(id, 'Unknown command "'..command_name..'"')
		end
		return 1
	end
	
	for _, f in pairs(CHAT_ATTACHMENT) do
		local v = ProtectedCall(f, id, txt)
		if v and v == 1 then ret = 1 end
	end
	
	return ret
end

function CreateChatAttachment(f)
	table.insert(CHAT_ATTACHMENT, f)
end

function CreateChat(name)
	return function (params)
		return function (lvl)
			return function (code)
				local f, e = loadstring("return function (id,txt,s,pos,args) "..code.."; end")
				if f then
					CHAT_CMD[name] = {f = f(),lvl = lvl,params = params}
				elseif e then
					error_get("CHAT CMD ERR ("..name.."): "..e)
				end
			end
		end
	end
end