import PropTypes from 'prop-types';
import React from 'react';
import ReactPaginate from 'react-paginate';
import UI from '../../config/ui/config';

/* This class handles the display of pages for the logbook */
class LogbookPager extends React.Component {
  constructor(props) {
    super(props);
    this.getTotalPageNumber = this.getTotalPageNumber.bind(this);
  }

  render() {
    if (this.getTotalPageNumber() <= 1) {
      return null;
    }

    if (this.props.eventCount === 0) {
      return null;
    }

    return (
      <ReactPaginate
        forcePage={this.props.activePage - 1}
        pageCount={this.getTotalPageNumber()}
        pageRangeDisplayed={1}
        previousLabel="<"
        nextLabel=">"
        marginPagesDisplayed={1}
        containerClassName={'pagination pagination-sm margin-top-bottom-0'}
        subContainerClassName={'pages pagination pagination-sm'}
        activeClassName={'active'}
        onPageChange={this.props.onPageClicked}
      />
    );
  }

  /**
   * Get the number of pages requested to display the data
   */
  getTotalPageNumber() {
    if (UI.logbook.EVENTS_PER_PAGE) {
      if (this.props.eventCount < UI.logbook.EVENTS_PER_PAGE) {
        return 1;
      }
      return Math.ceil(this.props.eventCount / UI.logbook.EVENTS_PER_PAGE);
    }
    // if in case of error, displays all items on the same page
    console.log(
      '[ERROR] Could not get the number of events per page. Check the config file.'
    );
    return 1;
  }
}

LogbookPager.propTypes = {
  /* Set the current page */
  activePage: PropTypes.number,
  /* the total number of events found by the server for a given search */
  eventCount: PropTypes.number.isRequired,
  /* Function triggered when the user clicks on a page */
  onPageClicked: PropTypes.func,
};

export default LogbookPager;
