<?php defined('SYSPATH') or die('No direct access allowed.');

/**
 * This class is the base used for common static methods that are used
 * for rendering.
 *
 * @package    lnApp
 * @category   lnApp/Helpers
 * @author     Deon George
 * @copyright  (c) 2009-2013 Deon George
 * @license    http://dev.leenooks.net/license.html
 */
abstract class lnApp_HTMLRender {
	protected $_unique_vals = array();
	protected $_x = 0;

	abstract protected function render();

	public function __call($name,$args=NULL) {
		if (! in_array($name,$this->_items))
			throw new Kohana_Exception('Unknown call to :name',array(':name'=>$name));

		$c = $this->_x;

		if (! $args)
			return static::$_data[$c][$name];

		// Strip out unique values
		if (in_array($name,$this->_unique_vals))
			foreach ($args as $u)
				foreach (static::$_data as $d)
					if (isset($d[$name]) AND $d[$name] == $u) {
						unset(static::$_data[$c]);

						return $this;
					}

		static::$_data[$c][$name] = array_pop($args);

		return $this;
	}

	public function __construct() {
		$this->_x = ++static::$_c;
	}

	/**
	 * Return the HTML to render the header images
	 */
	public function __toString() {
		if (! static::$_data)
			return '';

		if (empty(static::$_data[$this->_x]))
			$this->record();

		try {
			return $this->render();

		// Display the exception message
		} catch (Exception $e) {
			return $e->getMessage();
		}
	}

	public static function factory() {
		$x = get_called_class();
		return new $x;
	}

	public function record($x=NULL) {
		$this->_x = (is_null($x) OR empty(static::$_data[$x])) ? max(array_keys(static::$_data)) : $x;

		return $this;
	}

	/**
	 * Render all of these items
	 */
	public function render_all() {
		$output = '';

		for ($x=0; $x<static::$_c; $x++)
			if (isset(static::$_data[$x])) {
				$output .= (string)$this->record($x);
				unset(static::$_data[$x]);
			}

		return $output;
	}

	/**
	 * Set the space used between rendering output
	 */
	public static function spacer($spacer) {
		static::$_spacer = $spacer;
	}

	/**
	 * Add an item to be rendered
	 *
	 * @param array Item to be added
	 * @deprecated
	 */
	public static function add($item) {
		static::$_c = count(static::$_data);

		foreach (static::$_required_keys as $key)
			if (! isset($item[$key]))
				throw new Kohana_Exception('Missing key :key for image',array(':key'=>$key));

		// Check for unique keys
		if (isset(static::$_unique_vals) AND static::$_unique_vals)
			foreach (static::$_unique_vals as $v=>$u)
				foreach (static::$_data as $d)
					if (isset($d[$u]) && $d['data'] == $item['data'])
						return;

		static::$_data[++static::$_c] = $item;
	}
}
?>