<?php

class Waindigo_Listener_LoadClass
{
	protected $_class = null;
	protected $_extend = null;

	/**
	 * @param string $class
	 * @param array $extend
	 */
	public function __construct(&$class = '', array &$extend = array())
	{
		$this->_class = $class;
		$this->_extend = $extend;
	}

	/**
	 * @return array
	 */
	public function run()
	{
		$extends = $this->_getExtends();

		if (!empty($extends))
		{
    		foreach ($extends as $class => $extend) {
    			if ($class == $this->_class && !empty($extend)) {
    				if (is_array($extend)) {
    					foreach ($extend as $extendClass) {
    					    if (!in_array($extendClass, $this->_extend)) {
    						    $this->_extend[] = $extendClass;
    					    }
    					}
    				} else {
    					if (!in_array($extend, $this->_extend)) {
    				        $this->_extend[] = $extend;
    					}
    				}
    			}
    		}
		}
		return $this->_extend;
	}

	/**
	 * @return array
	 */
	protected function _run()
	{
		try {
			return $this->run();
		} catch (Exception $e) {
			return $this->_extend;
		}
	}

	/**
	 * @return array
	 */
	protected function _getExtends(){
		return array();
	}

	/**
	 * @return array
	 */
	public function getExtendedClasses()
	{
		return array_keys($this->_getExtends());
	}

	/**
	 * Gets the specified model object from the cache. If it does not exist,
	 * it will be instantiated.
	 *
	 * @param string $class Name of the class to load
	 *
	 * @return XenForo_Model
	 */
	public function getModelFromCache($class)
	{
		if (!isset($this->_modelCache[$class]))
		{
			$this->_modelCache[$class] = XenForo_Model::create($class);
		}

		return $this->_modelCache[$class];
	}

	/**
	 * Factory method to get the named load class code event listener.
	 * The class must exist or be autoloadable or an exception will be thrown.
	 *
	 * @param string Class to load
	 *
	 * @return Waindigo_Listener_LoadClass
	 */
	public static function create($class)
	{
		$createClass = XenForo_Application::resolveDynamicClass($class, 'waindigo_load_class');
		if (!$createClass)
		{
			throw new XenForo_Exception("Invalid code event listener '$class' specified");
		}

		return new $createClass;
	}

	/**
	 * Deprecated.
	 *
	 * @param $class
	 * @param $extend
	 * @deprecated
	 **/
	protected static function _extend($class, array &$extend)
	{
		if (!in_array($class, $extend))
		{
			$extend[] = $class;
		}
	}
}