USGN_DEFAULTDATA["pm"] = {}

CreateChat "!usgnpm" "<usgn> [text]" (0) [[
	if args >= 3 then
		local u = tonumber(s[2])
		local text = string.sub(txt, pos[3])
		
		if u then
			if string.len(text) > 0 then
				local p = USGNPlayer(u)
				if p then
					if p ~= id then
						msgc2(id, "[PM to] "..player(id,"name")..": "..text, 255, 255, 0)
						msgc2(p, "[PM from] "..player(id,"name")..": "..text, 255, 255, 0)
					else
						ErrorMSG(id, "You cannot send messages to yourself")
					end
				else
					msgc2(id, "[PM to] "..player(id,"name")..": "..text, 255, 255, 0)

					if not USGN_DATA[u] then
						table.insert(USGN[u]["pm"], "[PM from] #"..player(id,"usgn")..": "..text)
						SaveUSGN(u)
						DeleteUSGN(u)
					else
						table.insert(USGN[u]["pm"], "[PM from] #"..player(id,"usgn")..": "..text)
						SaveUSGN(u)
					end
				end
			else
				ErrorMSG(id, "You cannot send null messages")
			end
		else
			ErrorMSG(id, "Invalid USGN")
		end
	end
]]

CreateChat "!checkpm" "" (0) [[
	local i = 0
	for k, text in pairs(USER[id]["pm"]) do
		USER[id]["pm"][k] = nil
		i = i + 100
		AddTimer(i, false, msgc2, id, text, 255, 255)
	end
]]

addhook("join","player_count_pms")
function player_count_pms(id)
	if player(id, "usgn") > 0 then
		local pm_count = #USGN[player(id,"usgn")]["pm"]
		if pm_count > 0 then
			msgc2(id, "You have got "..pm_count.." private messages", 0, 255)
			msgc2(id, "Use !checkpm to read your private message", 0, 255)
		end
	end
end