<?php

/**
 * Core
 *
 * @author Arkadiusz Rychlik <a.rychlik at eppe.com.pl>
 */
class Rtn_SimpleTable_Paginator_Core extends Rtn_SimpleTable_Abstract_Block {

	/**
	 * Default parameters settings
	 * @var Rtn_SimpleTable_Paginator_Params
	 */
	public $params;
	
	/**
	 * @var int Current page
	 */
	public $currentPage;
	public $maxPage;
	public $minPage;
	
	private $rowsNumber;

	public function __construct(\Rtn_SimpleTable &$simpleTable) {
		parent::__construct($simpleTable);
		
		$this->params = new Rtn_SimpleTable_Paginator_Params();
		
		$this->rowsNumber = $this->simpleTable->dataSource->count();
		$this->maxPage = $this->_maxPage();
		$this->minPage = $this->_minPage();
	}
		
	public function setPage($pageNr) {
		if($this->_validatePage($pageNr)){
			$this->currentPage = $pageNr;
		}
		else{
			throw new Rtn_Exception(__('Page nr :page must be between :min and :max',[
				':page' => $pageNr,
				':min' => $this->_minPage(),
				':max' => $this->_maxPage(),
			]));
		}
	}
	
	public function nextPage() {
		$this->setPage(++$this->currentPage);
	}
	
	public function prevPage() {
		$this->setPage(--$this->currentPage);
	}
	
	protected function _validatePage($pageNr) {
		return ($pageNr<=$this->_maxPage()) && ($pageNr>=$this->_minPage());
	}
	
	protected function _maxPage(){
		return ceil($this->rowsNumber / $this->params->getRequiredParam('rowsPerPage'));
	}
	
	protected function _minPage(){
		return 0;
	}
	
}
