import React, { Component } from 'react';


require('./Pagination.scss');



class Pagination extends Component {

	constructor(props) {
		super(props);
		this.changePage = this.changePage.bind(this);
	}

	changePage(e, page) {
		e.preventDefault();
		const { onPageChanged, paging, status } = this.props;
		
		if (page < 0 || page > paging.pagesCount || status == 'pending') {
			//do nothing
			return;
		}
		if (typeof onPageChanged == "function") {
			onPageChanged(page);
		}
	}

	render() {
		const { paging, onPageChanged, status, disabled } = this.props;
		if (!paging || !paging.pagesCount) {
			return null;
		}

		const page = (paging.page || 0) * 1;
		const count = (paging.pagesCount || 1) * 1;

		//numbers
		const links = [];
		const min = Math.max(page - 1, 1);
		const max = Math.min(page + 2, count - 1);
		for (let i = min; i < max; i++) {
			links.push({page: i, num: i + 1});
		}

		return (
			<div className="pagingContainer">
				<div className={ disabled ? "disabled paging" : "paging" }>
					<button href="#" disabled={ disabled || page < 1 || status == 'pending'} onClick={(e) => { this.changePage(e, page - 1) } }>&lt;</button>
					<a href="#" className={ page == 0 ? "active" : null } onClick={(e) => {!disabled && this.changePage(e, 0)}}>1</a>
					{count > 1 && page > 2 && <span>&hellip;</span> }
					{links.map((item) => {
					    return <a href="#" className={ page ==  item.page ? "active" : null } key={item.page} onClick={(e) => { !disabled && this.changePage(e, item.page)}}>{item.num}</a>
					})}
					{ count > 1 && page < count - 3 && <span>&hellip;</span> }
					{ count > 1 && <a href="#" className={page == count - 1 ? "active" : null} onClick={(e) => { !disabled && this.changePage(e, count - 1)}}>{count}</a> }
					<button href="#" disabled={ disabled || page >= count - 1 || status == 'pending'} onClick={(e) => {this.changePage(e, page + 1)}}>&gt;</button>
				</div>
			</div>
		)	
	}

	

}



export default Pagination;