import { PageWindowResult } from '../types'

const calculationStartPageAndEndPage = (
  allPages: number,
  maxVisiblePages: number,
  currentPage: number
): PageWindowResult => {
  if (allPages <= 0) {
    return { startPage: 1, endPage: 0 }
  }

  const visiblePages = Math.max(1, maxVisiblePages)

  if (allPages <= visiblePages) {
    return { startPage: 1, endPage: allPages }
  }

  const maxPagesBeforeCurrentPage = Math.floor(visiblePages / 2)
  const maxPagesAfterCurrentPage = Math.ceil(visiblePages / 2) - 1
  const isNearStart = currentPage <= maxPagesBeforeCurrentPage
  const isNearEnd = currentPage + maxPagesAfterCurrentPage >= allPages

  const startPage = (() => {
    if (isNearStart) {
      return 1
    }

    if (isNearEnd) {
      return allPages - visiblePages + 1
    }

    return currentPage - maxPagesBeforeCurrentPage
  })()

  const endPage = (() => {
    if (isNearStart) {
      return visiblePages
    }

    if (isNearEnd) {
      return allPages
    }

    return currentPage + maxPagesAfterCurrentPage
  })()

  return { startPage, endPage }
}

export default calculationStartPageAndEndPage
