--------------------- Polite Notice ---------------------
-- YaLB was created by Daniel Astbury (jnz)            --
-- The source is avaliable to anyone, however          --
-- please do not take it can claim it yours.           --
-- Please follow my example and release your own.      --
-----------------------Thank you-------------------------


Moderators = {}
Moderator = {Nick = "", IRCNick = "", Status = ""}
    
function Moderator:new (o)
	o = o or {}
	setmetatable(o, self)	
	self.__index = self
	return o
end

function Is_Moderator(Nick, IRC, Channel)
	for i,v in pairs(Moderators) do
		if IRC == true then
			if string.lower(v.IRCNick) == string.lower(Nick) then
				local x = Get_IRC_Status(Nick, Channel)
				if Status_Level(x) <= Status_Level(v.Status) then
					return x
				else
					return v.Status
				end
			end
				
		else
			if string.lower(v.Nick) == string.lower(Nick) then
				local x = Find_Player(Nick)
				if x <= 0 then
					return ""
				end
				
				x = Players[x].Status
				if Status_Level(x) <= Status_Level(v.Status) then
					return x
				else
					return v.Status
				end	
			end
		end
	end
	return nil
end

function Moderator_Game_Nick(Nick)
	for i,v in pairs(Moderators) do
		if string.lower(v.IRCNick) == string.lower(Nick) then
			return v.Nick
		end
	end
	
	return nil
end	

function Status_Name(Status)
	if Status == "~" then
		return "Founder"
	elseif Status == "&" then
		return "Administrator"
	elseif Status == "@" then
		return "Moderator"
	elseif Status == "%" then 
		return "Half Moderator"
	elseif Status == "+" then
		return "Temporary Moderator"
	end
	
	return ""
end

function Status_Level(Status)
	if Status == "~" then
		return 5
	elseif Status == "&" then
		return 4
	elseif Status == "@" then
		return 3
	elseif Status == "%" then 
		return 2
	elseif Status == "+" then
		return 1
	end
	
	return 0
end

function Command_Allowed(Who, IsIRC, Command, Channel)
	local Status = ""
	if IsIRC == true then
		Status = Is_Moderator(Who, true, Channel)
	else
		Status = Is_Moderator(Get_Player_Name_By_ID(Who), false, "")
	end
		
	local block = Find_Block("Moderators", "Cloaks")
	if block == nil then	
		return false
	end
	
	local key = ""
	local group = ""
	if Status == "~" then
		key = "founder"
	elseif Status == "&" then
		key = "admin"
	elseif Status == "@" then
		key = "full"
	elseif Status == "%" then
		key = "half"
	elseif Status == "+" then
		key = "tmp"
	end
	
	if key == "" then
		group = "*"
	else
		group = block.Keys[key] .. "*"
	end
	
	if string.match(group, Command.Group) ~= nil then
		return true
	else
		return false
	end
end

function Load_Moderators()
	Moderators = {}
	local mods = Find_Block("Moderators")
	if mods == nil then 
		return
	end
	
	for i,v in pairs(mods.Next_Level) do
		if i ~= "cloaks" then
			table.insert(Moderators, Moderator:new({Nick = i, IRCNick = v.Keys['IRCNick'], Status = v.Keys['cloak']}))
		end
	end	
end