<?php
namespace KIF\Page;

/**
 * 分页类
 * 需设定以下样式:
 * page-prev:上一页
 * page-next:下一页
 * page-more:更多,即...
 * page-current:当前页
 * @author gaoxiaogang@gmail.com
 */
use KIF\Verify;
use Exception;

class Page {
	/**
	 * 
	 * 总页数
	 * @var int
	 */
	protected $pages;
	
	/**
	 * 
	 * 当前页
	 * @var int
	 */
	protected $page;
	
	protected $first_num = 2;
	
	protected $end_num = 2;
	
	protected $nearby_num = 2;
	
	/**
	 * 
	 * url模版
	 * 必须用 {page} 代表页码占位符。比如 http://misc.kimiss.com/comments/19933/{page}
	 * @var string
	 */
	protected $url_tpl;
	
	/**
	 * 
	 * Enter description here ...
	 * @param int $nums 总结果数量
	 * @param string $url_tpl url模版,必须用 {page} 代表页码占位符。比如 http://misc.kimiss.com/comments/19933/{page}
	 * @param int $page 当前页码
	 * @param int $size 每页显示多少个
	 * @return Page
	 */
	public function __construct($nums, $url_tpl, $cur_page = 1, $size = 20) {
		if (!Verify::unsignedInt($cur_page)) {
			throw new Exception("invalid cur_page param: {$cur_page}");
		}
		$this->pages = ceil($nums/$size);
		if ($cur_page > $this->pages) {
			$cur_page = $this->pages;
		}
		$this->page = $cur_page;
		$this->url_tpl = $url_tpl;
	}
	
	/**
	 * 
	 * 获取指定页面的url
	 * @param int $page
	 * @return string
	 */
	private function pageUrl($page) {
		$url = str_replace('{page}', $page, $this->url_tpl);
		$url = str_replace('%7Bpage%7D', $page, $url);// 支持url被转义后的
		return $url;
	}
	
	public function html() {
		$html = '';
		
		# 显示上一页
		if ($this->page > 1) {
			$prev_page = $this->page - 1;
			$html .= <<<PAGE
				<a class="page-prev" data-page="{$prev_page}" href="{$this->pageUrl($prev_page)}">
				上一页
				<i></i>
				</a>
PAGE;
		}
		
		# 显示第1、2页
		for ($i=1; $i<=$this->first_num; $i++) {
			if ($i >= $this->page-$this->nearby_num) {
				continue;
			}
			$html .= <<<PAGE
				<a data-page="{$i}" href="{$this->pageUrl($i)}">
				{$i}
				</a>
PAGE;
		}
		
		if ($this->page > ($this->first_num+$this->nearby_num+1)) {
			$html .= '<span class="page-more">...</span>';
		}
		
		for ($i=$this->page-$this->nearby_num; $i <= $this->page+$this->nearby_num; $i++ ) {
			if ($i < 1) {
				continue;
			}
			if ($i > $this->pages) {
				continue;
			}
			if ($i == $this->page) {
				$html .= "<span class=\"page-current\">{$i}</span>";
			} else {
				$html .= <<<PAGE
				<a data-page="{$i}" href="{$this->pageUrl($i)}">
				{$i}
				</a>
PAGE;
			}
		}
		
		if ($this->page < $this->pages-$this->end_num-$this->nearby_num) {
			$html .= '<span class="page-more">...</span>';
		}
		
		# 显示倒数第1、2页
		for ($i=$this->pages-$this->end_num+1; $i<=$this->pages; $i++) {
			if ($i <= $this->page+$this->nearby_num) {
				continue;
			}
			$html .= <<<PAGE
				<a data-page="{$i}" href="{$this->pageUrl($i)}">
				{$i}
				</a>
PAGE;
		}
		
		# 显示下一页
		if ($this->page < $this->pages) {
			$next_page = $this->page + 1;
			$html .= <<<PAGE
				<a class="page-next" data-page="{$next_page}" href="{$this->pageUrl($next_page)}">
				下一页
				<i></i>
				</a>
PAGE;
		}
		
		return $html;
	}
}