/**
 *  minimal pager item count, must be odd number
 */
export const MINIMAL_PAGER_ITEM_COUNT = 7;
/**
 * It generates an array of numbers and ellipsis that represent the pager items
 *
 * @param {number} current - the current page number
 * @param {number} total - the total number of pages
 * @param {number} [pagerCount=7] - the count of pager items, must be odd number
 * @returns {(number | string)[]} returns an array of page numbers and placeholders
 */
export const generatePagerItems = (current, total, pagerCount = MINIMAL_PAGER_ITEM_COUNT) => {
  const ellipsisPlaceholder = '...';
  if (pagerCount < MINIMAL_PAGER_ITEM_COUNT) {
    throw new Error(`Must allow at least ${MINIMAL_PAGER_ITEM_COUNT} pager items`);
  }
  if (pagerCount % 2 === 0) {
    throw new Error(`Must allow odd number of pager items`);
  }
  if (total < pagerCount) {
    return Array(total)
      .fill(0)
      .map((_, index) => index + 1);
  }
  const left = Math.max(1, Math.min(total - pagerCount + 1, current - Math.floor(pagerCount / 2)));
  const items = new Array(pagerCount);
  for (let i = 0; i < pagerCount; i += 1) {
    items[i] = i + left;
  }
  if (Number(items[0]) > 1) {
    items[0] = 1;
    items[1] = ellipsisPlaceholder;
  }
  if (Number(items[items.length - 1]) <= total - 1) {
    items[items.length - 1] = total;
    items[items.length - 2] = ellipsisPlaceholder;
  }
  return items;
};
