<?php

/**
 * THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 *
 * @package fusionLib
 * @copyright Copyright (c) 2012 - 2013 fusionLib. All rights reserved.
 * @link http://fusionlib.com
 */

/**
 * flWidgetBreadcrumb Class
 *
 * Create and manage breadcrumb trails.
 *
 * @package fusionLib
 */
class flWidgetBreadcrumb {

	/**
	 * The crumbs.
	 *
	 * @var array
	 */
	private $crumbs = array();

	/**
	 * The CSS class to apply to the table.
	 *
	 * @var string
	 */
	protected $css = 'breadcrumbwidget';

	/**
	 * Flags if last crumb should be a link or not.
	 *
	 * @var bool
	 */
	protected $linkLast = false;

	/**
	 * Set the CSS class to use.
	 *
	 * @param string $css The CSS class, default is 'breadcrumbwidget'.
	 * @return flWidgetBreadcrumb This object.
	 */
	function setClass($css) {
		$this->css = $css;
		return $this;
	}

	/**
	 * Set last crumb should be a link.
	 *
	 * @param bool $linkLast true if the last crumb in the trail should be a link; else false.
	 * @return flWidgetBreadcrumb This object.
	 */
	function setLastAsLink($linkLast = true) {
		$this->linkLast = $linkLast;
		return $this;
	}

	/**
	 * Add a crumb to the trail.
	 *
	 * @param string $name The anchor text for the link.
	 * @param string $link The link URI
	 * @return flBreadcrumb This object.
	 */
	function addCrumb($name, $link) {
		$this->crumbs[] = array($name, $link);
		return $this;
	}

	/**
	 * Get the crumbs as a string.
	 *
	 * @param string $separator The string to place between the crumbs.
	 * @return string The string holding the combined crumbs.
	 */
	function getCrumbs($separator = ' / ') {
		$crumbs = '';
		$lastCrumb = count($this->crumbs) - ($this->linkLast ? 0 : 1);
		foreach($this->crumbs as $i => $d) {
			if($i) $crumbs .= $separator;
			if($i == $lastCrumb)
				$crumbs .= "<span>$d[0]</span>";
			else
				$crumbs .= "<a href=\"$d[1]\">$d[0]</a>";
		}
		return $crumbs;
	}

	/**
	 * Get the crumbs as an array.
	 *
	 * @return array The array of crumbs, 0 = text, 1 = URI.
	 */
	function getCrumbsArray() {
		return $this->crumbs;
	}

	/**
	 * Render the crumbs as a HTML ul list.
	 *
	 * @return string The HTML to create the trail.
	 */
	function render() {
		$crumbs = '';
		if(count($this->crumbs)) {
			$lastCrumb = count($this->crumbs) - ($this->linkLast ? 0 : 1);
			$crumbs .= '<ul class="' . $this->css . "\">\n";
			foreach($this->crumbs as $i => $d) {
				if($i == $lastCrumb)
					$crumbs .= "<li><span>$d[0]</span></li>\n";
				else
					$crumbs .= "<li><a href=\"$d[1]\">$d[0]</a></li>\n";
			}
			$crumbs .= "</ul>\n";
		}
		return $crumbs;
	}
}
