<?php

/* Switch from page to page to display a list of data */

class PageSwitch
{
	public $sPageVar;
	public $iPageNumber;
	
	private $iItemNb;
	private $iLimit;
	
	private $sRefPage;
	private $sExtraRefPageVar;
	
	private $sNextPageLinkTitle;
	private $sPrevPageLinkTitle;
	
	public function __construct($sPageVar, $iTotalItemNb, $iLimit, $sExtraRefPageVar='')
	{
		$this->sPageVar = $sPageVar;
		$this->iItemNb = $iTotalItemNb;
		$this->iLimit = $iLimit;
		$this->sExtraRefPageVar = $sExtraRefPageVar;
		
		//parse url
		$asUrlParts = parse_url($_SERVER['REQUEST_URI']);
		if(isset($asUrlParts['query']))
		{
			parse_str($asUrlParts['query'], $asUrlVariables);
		
			$this->sRefPage = $asUrlVariables['page'];
			$this->iPageNumber = isset($asUrlVariables[$this->sPageVar])?$asUrlVariables[$this->sPageVar]:1;
		}
		else
		{
			$this->sRefPage = DEFAULT_LOGGED_PAGE;
			$this->iPageNumber = 1;
		}
				
		$this->setNextPageLinkTitle();
		$this->setPrevPageLinkTitle();
	}
	
	public function setNextPageLinkTitle($sTitle='>')
	{
		$this->sNextPageLinkTitle = $sTitle;
	}
	public function setPrevPageLinkTitle($sTitle='<')
	{
		$this->sPrevPageLinkTitle = $sTitle;	
	}
	
	public function getItemStartPointer()
	{
		return (max(0, $this->iPageNumber-1))*$this->iLimit;
	}
	
	public function getItemRange()
	{
		$iItemStartPointer = $this->getItemStartPointer();
		return array('start'=>$iItemStartPointer+1, 'end'=>min($this->iItemNb, $iItemStartPointer+$this->iLimit));
	}
	
	public function getNextLink()
	{
		return $this->isNextPage()?$this->getPage($this->sNextPageLinkTitle, 1):'';
	}
	
	public function getPrevLink()
	{
		return $this->isPrevPage()?$this->getPage($this->sPrevPageLinkTitle, -1):'';
	}
	
	private function isNextPage()
	{
		return (($this->iItemNb - ($this->iPageNumber-1)*$this->iLimit) > $this->iLimit);
	}
	
	private function isPrevPage()
	{
		return ($this->iPageNumber > 1);
	}
	
	private function getPage($sTitle, $iDir)
	{
		$iPageNb = max(1, $this->iPageNumber + $iDir); 
		return getHtml($sTitle, 'a', 'XButton rounded', 'font-size:12px;border-color:white;', array('href'=>'?page='.$this->sRefPage.'&'.$this->sPageVar.'='.$iPageNb));	
	}
}