package com.apobates.forum.trident.tag;

import java.io.IOException;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.SimpleTagSupport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.apobates.forum.utils.Commons;
import com.apobates.forum.utils.Pagination;
/**
 * 简易的分页标签:{上一页 | 当前码面 / 总页数 | 下一页}
 * 
 * @author xiaofanku
 * @since 20190731
 */
public class EasyPaginationTag extends SimpleTagSupport{
	// 总数量(必需)
	private int total;
	// 不代分页参数的地址(必需)
	private String url;
	// 每页显示的记录数(必需)
	private int size;
	private final static String NEWLINE = Commons.NEWLINE;
	private final static Logger logger = LoggerFactory.getLogger(EasyPaginationTag.class);

	@Override
	public void doTag() throws JspException, IOException {
		PageContext pc = (PageContext) getJspContext();
		HttpServletRequest request = (HttpServletRequest) pc.getRequest();

		int page = 1;
		try {
			page = Integer.valueOf(request.getParameter("p"));
		} catch (NumberFormatException e) {
			if (logger.isDebugEnabled()) {
				logger.debug("[PT]转化动态分页页码数失败", e);
			}
		}
		if (logger.isDebugEnabled()) {
			String descrip = "[EasyPaginationTag]" + NEWLINE;
			descrip += "/*----------------------------------------------------------------------*/" + NEWLINE;
			descrip += " request url: " + url + NEWLINE;
			descrip += " page number: " + page + NEWLINE;
			descrip += " page size: " + size + NEWLINE;
			descrip += " record total: " + total + NEWLINE;
			descrip += "/*----------------------------------------------------------------------*/" + NEWLINE;
			logger.debug(descrip);
		}
		//无记录不输出分页标签
		if(total == 0){
			// 输出标签体
			getJspContext().getOut().print("");
			return;
		}
		Pagination frontPage = new Pagination(url, page, size, total);
		// 有序Map
		Map<String, String> struct = frontPage.draw(true);
		getJspContext().setAttribute("totalPageSize", frontPage.showMaxPageNumber());
		getJspContext().setAttribute("currentPage", page);
		getJspContext().setAttribute("prevPageLink", struct.get(Pagination.PAGE_PREV));
		getJspContext().setAttribute("nextPageLink", struct.get(Pagination.PAGE_NEXT));
		// 输出标签体
		getJspBody().invoke(null);
	}

	public void setTotal(int total) {
		this.total = total;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public void setSize(int size) {
		this.size = size;
	}
}
