<?php
/**
 * Zásuvný modul, který nastaví v kontrolleru paginator
 *
 */
class MyWeb_Controller_Plugin_Paginator extends Zend_Controller_Plugin_Abstract  
{
	
	private $_model = NULL;
	private $_pager = NULL;
	private $_data = NULL;
	
	/**
	 * nastavi data pro model
	 * Enter description here ...
	 */
	public function setData($data)
	{
		$this->_data = $data;
	}
	
	/**
	 * nastavi model pro paginator
	 * Enter description here ...
	 */
	public function setModel($model)
	{
		$this->_model = $model;
	}
	
	/**
	 * vrati object paginator
	 * Enter description here ...
	 */
	public function getPaginator()
	{
		$this->createPaginator();
		return $this->_pager;
	}
	
	/**
	 * metoda vytvori paginator
	 * Enter description here ...
	 * @throws Exception
	 */
	private function createPaginator()
	{
			if (empty($this->_model)){
				$zprava = "MyWeb_Controller_Plugin_Paginator: Not exists model: "."\n";
        		throw new Exception($zprava);
			}
			if (empty($this->_data)){
				$zprava = "MyWeb_Controller_Plugin_Paginator: Not exists data: "."\n";
        		throw new Exception($zprava);
			}
			
			// nazev primarniho klice
        	$primaryKey = current($this->_model->getStorage()->info('primary'));
        	// ziska adapter
        	$db = $this->_model->getStorage()->getAdapter();
        	//ziska select pro fetchEntry
        	$select = $this->_model->getFetchEntrySelect($this->_data);
        	//echo "<p>".$select."</p>";
        	// nastaveni pocatecnich hodnot pro paginator v poli get
			$sortField = $this->_request->getParam('s',false) ? htmlentities($this->_request->getParam('s')) : $primaryKey;
        	$sortDir = $this->_request->getParam('d',false) ? $this->_request->getParam('d') : '0';
        	
        	if ($sortDir >= 3){
        		$sortDir = 0;
        	}
        	$sort[0] = 'asc';
        	$sort[1] = 'desc';
        	$sort[2] = 'none';
        	$sortDir = htmlentities($sort[$sortDir]);
        	
        	$db->setFetchMode(Zend_Db::FETCH_NUM);
        
        	$pagerSelect = $select;
        	if (2 != $this->_request->getParam('d')){
        		$pagerSelect = $select->order("$sortField $sortDir");
        	}
        	// provede se select, ktery kontroluje zda existuje alespon 1 zaznam
        	$data = $this->_model->fetchEntries($this->_data);
        	if (count($data) !== 0){
        		// initialize pager with data set
        		$pager = new Zend_Paginator(
        					new Zend_Paginator_Adapter_DbSelect(
        						$pagerSelect
        						)
        					);
        		$page = (int) $this->_request->getParam('page',1);
        		$pager->setCurrentPageNumber($page);
        		$this->_pager = $pager;
        	}
	}
}