/*

*
* AUTHOR: paradox
*
* PURPOSE: Handles providing some needed utility functions.
*

*/

//-/~ Protected Function
function majestic.IsProtected( Func )
    if not isfunction( Func ) then return false end 

    return getfenv( Func ) == getfenv( )
end

//-/~ Protected Table
function majestic.ProtectedTable( Object )
    if not istable( Object ) then return false end 

    return Object == majestic or Object == getfenv( )
end

//-/~ Protected Directory
function majestic.ProtectedDirectory( Directory )
    if not isstring( Directory ) then return false end 

    return Directory:StartsWith( 'majestic/' ) or Directory:StartsWith( 'lua/majestic/' ) 
end

//-/~ Load File
function majestic.LoadFile( FileDir )
    local Code = file.Read( FileDir, 'GAME' )

    if #Code <= 0 then return end 

    majestic.Print( 'Loading script "' .. FileDir .. '".' )

    -- `xpcall` so we don't print to the serverside console or get logged.
    xpcall( majestic.loadCode, function( Error )
        majestic.Print( 'Failed to load script "' .. FileDir .. '", debug info dumped.' )

        -- Print debug information
        print( debug.traceback( ) )

        MsgN( '\n' .. Error )
    end, Code )
end

//-/~ Print
function majestic.Print( Text )
    MsgC( color_white, '[', color_purple, 'majestic', color_white, '] ' .. Text .. '\n' )
end

//-/~ Console Commands
concommand.Add( 'majestic_loadscript', function( _, __, ___, Directory )
    if not Directory then return end

    -- Insure we are in the Majestic base folder.
    Directory = 'majestic/' .. Directory

    -- Run our LoadFile (if possible).
    if file.IsDir( Directory, 'GAME' ) then -- Loop through directory provided.
        local Files = file.Find( Directory .. '/*.lua', 'GAME' )

        for i = 1, #Files do 
            majestic.LoadFile( Directory .. '/' .. Files[ i ] )
        end
    elseif file.Exists( Directory, 'GAME' ) then -- Run direct lua file provided.
        majestic.LoadFile( Directory )
    else 
        majestic.Print( 'We were unable to find directory or file "' .. Directory .. '"' )
    end
end )