
// Globals that we are going to use
local pairs = pairs
local unpack = unpack
local Msg = Msg

/*---------------------------------------------------------
   Name: hook
   Desc: For scripts to hook onto Gamemode events
---------------------------------------------------------*/
module("hook")


// Local variables
local Hooks = {}


// Exposed Functions

/*---------------------------------------------------------
   Name: Add( event_name, name, function )
   Desc: Adds a hook
   Usage: hook.Add( "Think", "MyHookName", MyThinkFunction )
---------------------------------------------------------*/
function Add( event_name, name, func )

	if (Hooks[ event_name ] == nil) then
		Hooks[ event_name ] = {}
	end

	Hooks[ event_name ][ name ] = func
end

/*---------------------------------------------------------
   Name: Remove( name )
   Desc: Removes a hook
   Usage: Remove( "Think", "MyHookName" )
---------------------------------------------------------*/
function Remove( event_name, name )

	Hooks[ event_name ][ name ] = nil

end

/*---------------------------------------------------------
   Name: Call( name, args )
   Desc: Called by the engine to call a gamemode hook
---------------------------------------------------------*/
function Call( name, gm, ... )

	if ( Hooks[ name ] ~= nil ) then
		for k, v in pairs( Hooks[ name ] ) do 
			
			if ( v == nil ) then
			
				Msg("Hook error! Hook '"..k.."' tried to call a nil function!\n")
				break;
			
			else
				// Call hook function
				local retval = v( unpack(arg) )
				
				// Allow gamemodes to override return values
				if (retval != nil) then
					return retval
				end
			end
			
		end
	end
	
	if (gm[ name ] == nil) then
		gm[ name ] = function() end
		Msg( "GAMEMODE ERROR: Function '"..name.."' Is Missing!\n" )
		return nil
	end
	
	// Call the actual gamemode function
	return gm[ name ]( gm, unpack(arg) )
	
end

