import React, { Component } from "react";
import Image from "next/image";
import Link from "next/link";
import moment from "moment";

class NewsCard extends Component 
{
	constructor(props)
	{
		super(props);
		this.state = {
		};
	}

	_onPagePress = (page) => 
	{
		this.props.onPagePress(page);
	}

	_renderPageNumber = (page, p, index) => 
	{
		return (
			<li key={ index } style={ p === page ? { fontWeight: "bold" } : {} }>
				<a style={{ cursor: "pointer" }} onClick={ () => p === page ? {} : this.props.onPage(p) }>{ p }</a>
			</li>
		)
	}

	render()
	{
		const { pages, showAll } = this.props;
		let page = this.props.page;
		if(page < 0) { page = pages; }

		let firstPage = 1;
		let lastPage = pages;

		if(lastPage <= 1)
		{
			return null;
		}

		let pagesLinks = [];
		let p = page;

		if(lastPage > 6)
		{
			if(p === lastPage)
			{
				p = p - 3;
			}
			else
			{
				if(p <= 3) { p = p - (p-1); };
				if(p > 3) { p = p - 1; }
				//if(p > (lastPage - 3)) { p = p - 4; }
				if(p > (lastPage - 3))
				{
					p = p - (lastPage - (p+1));
				}
			}
		}

		if(lastPage > 6)
		{
			for(let i = 0; i < 7; i++)
			{
				if(i == 0)
				{
					pagesLinks.push(this._renderPageNumber(page, firstPage, i));
				}
				else if(i == 1)
				{
					if(p >= 3)
					{
						pagesLinks.push(<li key={i}>...</li>);
					}
					else
					{
						if(p > 1)
						{
							pagesLinks.push(this._renderPageNumber(page, p, i));
						}
						p++;
					}
				}
				else if(i == 5)
				{
					if(p < (lastPage))
					{
						pagesLinks.push(<li key={i}>...</li>);
					}
				}
				else if(i == 6)
				{
					pagesLinks.push(this._renderPageNumber(page, lastPage, i));
				}
				else
				{
					pagesLinks.push(this._renderPageNumber(page, p, i));
					p++;
				}
			}
		}
		else
		{
			for(let i = 0; i < lastPage; i++)
			{
				pagesLinks.push(this._renderPageNumber(page, i+1, i));
			}
		}

		return (
			<div className="pagination">
				<ul>
				{ page !== 1 && (<li><a style={{ cursor: "pointer" }} onClick={ () => this.props.onPage(page - 1) }>{`<`}</a></li>) }
				{ pagesLinks }
				{ page < pages && (<li><a style={{ cursor: "pointer" }} onClick={ () => this.props.onPage(page + 1) }>{`>`}</a></li>) }
				{ showAll && (
					<li>
						<a style={{ cursor: "pointer" }} onClick={ this.props.onAll }>Все</a>
					</li>
				) }
				</ul>
			</div>
		)
	}
}

export default NewsCard;
									