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

/**
 * This is class helps with rendering JPGraph Gantt images.
 *
 * @package    lnApp
 * @subpackage JPGraph
 * @category   Helpers
 * @author     Deon George
 * @copyright  (c) 2010 Deon George
 * @license    http://dev.leenooks.net/license.html
 */
class lnApp_JPGraph_Gantt extends JPGraph {
	// Our JPGraph object
	public $jpgraph;
	private $_count;
	private $_items = array();

	public function __construct() {
		// Run through our parent checks
		$jpgraph = parent::__construct();

		if (! file_exists($jpgraph.'/jpgraph_gantt.php'))
			throw new Kohana_Exception('jpgraph_gantt.php must be installed in '.$jpgraph);

		require_once $jpgraph.'/jpgraph_gantt.php';

		$this->jpgraph = new GanttGraph(0,0,'auto');
		return $this;
	}

	// Add a new line item to the Gantt Chart
	public function add($summary,$start,$end) {
		$this->_count = count($this->_items);

		$this->_items[$this->_count]['summary'] = $summary;
		$this->_items[$this->_count]['start'] = $start;
		$this->_items[$this->_count]['end'] = $end;

		return $this;
	}

	public function caption($value) {
		$this->_items[$this->_count]['caption'] = $value;

		return $this;
	}

	public function csim($value) {
		$this->_items[$this->_count]['csim'] = $value;

		return $this;
	}

	public function progress($value) {
		$this->_items[$this->_count]['progress'] = $value;

		return $this;
	}

	public function sort($value) {
		$this->_items[$this->_count]['sort'] = $value;

		return $this;
	}

	// This will compile the gantt and output a URL that has the image
	public function draw($name) {
		// Sort our items by sort criteria.
		Sort::MAsort($this->_items,'sort,summary',0);

		$c = 0;
		$ls = '';
		foreach ($this->_items as $item) {
			// Put a gap between our priority items.
			if ($c AND ($lp != $item['sort']))
				$c++;

			if ($ls != $item['summary'])
				$c++;

			$lp = $item['sort'];
			$ls = $item['summary'];

			$activity = new GanttBar($c,$item['summary'],$item['start'],$item['end']);
			$activity->progress->Set($item['progress']);
			$activity->caption ->Set($item['caption']);
			$activity->SetCSIMTarget('#',($item['csim'] ? $item['csim'] : 'NoCSIM'));
			$activity->title->SetCSIMTarget('#',($item['csim'] ? $item['csim'] : 'NoCSIM'));

			$this->jpgraph->Add($activity);
		}

		$tmpfile = '/tmp/'.$name.'.png';
		$file = 'session/'.$name.'.png';

		$this->jpgraph->Stroke($tmpfile);
		Session::instance()->set($file,file_get_contents($tmpfile));
		unlink($tmpfile);

		return $file;
	}
}
?>
