/**
 * This function converts a page number to an index range of the form {startIndex, endIndex}.
 * @param {integer or string } page current page
 * @param {integer} eventsPerPage number of events per page
 * @param {integer} foundEventCount total number of events found
 * @returns {obj} the index range corresponding to the requested page {start: xxx, end: yyy}
 */
export function convertPageToPageEventIndexes(
  page,
  eventsPerPage,
  foundEventCount
) {
  if (page && eventsPerPage && foundEventCount) {
    if (page instanceof String) {
      page = parseInt(page, 10);
    }

    let endIndex = eventsPerPage * (page - 1) + eventsPerPage - 1;
    if (Math.ceil(foundEventCount / eventsPerPage) === page) {
      //user asks for the last page
      endIndex = foundEventCount - 1;
    }

    return {
      start: eventsPerPage * (page - 1),
      end: endIndex,
    };
  }
  return {
    start: 0,
    end: eventsPerPage,
  };
}

/**
 * Check whether the requested page event indexes are already available on the client side
 * @param {*} pageEventIndexes requested page event indexes
 * @param {*} downloadedEventIndexes already downloaded event indexes
 * @returns {boolean} true when page event indexes are already available on the client. False otherwise.
 */
export function isRangeAvailableOnTheClient(
  pageEventIndexes,
  downloadedEventIndexes
) {
  function isIndexObjectUsable(indexObject) {
    return (
      indexObject && indexObject.start !== null && indexObject.end !== null
    );
  }

  if (
    isIndexObjectUsable(pageEventIndexes) &&
    isIndexObjectUsable(downloadedEventIndexes)
  ) {
    return (
      pageEventIndexes.start >= downloadedEventIndexes.start &&
      pageEventIndexes.start <= downloadedEventIndexes.end &&
      pageEventIndexes.end >= downloadedEventIndexes.start &&
      pageEventIndexes.end <= downloadedEventIndexes.end
    );
  }
  return null;
}
