<?php namespace Majestic;
/**
 * @copyright NetMonsters <team@netmonsters.ru>
 * @link http://netmonsters.ru
 * @package Majestic
 * @subpackage Load
 * @since 2010-02-24
 */

class Load
{

    static protected $file;

    static protected $autoload;

    static protected $exclude = array();

    static protected $builder = null;

	/**
	 * @var \Composer\Autoload\ClassLoader
	 */
	static protected $class_loader;

	static public function setClassLoader($class_loader) {
		self::$class_loader = $class_loader;
	}

    /**
     * Add exclude path for autoload. Should be called before setAutoloadFrom
     * @static
     * @param array $exclude list of relative path (from project root)
     * @return void
     */
    static public function setExclude($exclude = array())
    {
        if (!is_array($exclude)) {
            $exclude = array($exclude);
        }
        self::$exclude = array_merge(self::$exclude, $exclude);
    }

    static public function setAutoloadFrom($file)
    {
        self::$file = $file;
        if (!file_exists(self::$file)) {
            self::buildAutoload();
        }
        self::$autoload = require(self::$file);
        spl_autoload_register(array(
            __CLASS__,
            'autoload'));
    }

    static public function autoload($class)
    {
        if (isset(self::$autoload[$class])) {
            require(PATH . self::$autoload[$class]);
            return;
        }
        if (Config::get('DEBUG')) {
            if (!isset(self::$autoload[$class])) {
                self::buildAutoload();
            }
            if (isset(self::$autoload[$class])) {
                require(PATH . self::$autoload[$class]);
            }
        }
    }

    static public function getFilePath($class)
    {
	    if (self::$class_loader) {
		    return self::$class_loader->findFile($class);
	    } else {
            return self::$autoload[$class];
	    }
    }

    static protected function buildAutoload()
    {
        ignore_user_abort(true);
        $dir = dirname(self::$file);
        if (!file_exists($dir) && !mkdir($dir)) {
            trigger_error('Can\'t create directory: "' . $dir . '"', E_USER_ERROR);
        }

        $scan = array(PATH . '/' . APP . '/src', PATH . '/lib', PATH . '/vendor');
        $exclude = array_merge(self::$exclude, array(PATH . '/.git', PATH . '/lib/core/tests', PATH . '/lib/core/.git'));


        if (!self::$builder) {
            require_once(PATH . '/lib/core/util/AutoloadBuilder.php');
            require_once(PATH . '/lib/core/util/AsciiSortedIterator.php');
            self::$builder = new AutoloadBuilder(self::$file, $scan, $exclude);
        }
        self::$builder->build();
        ignore_user_abort(false);
    }
}