const inquirer = require('inquirer')
const fetch = require('node-fetch')

inquirer.registerPrompt('lazy-list', require('../src'))

const pageSize = 5

const fetchMore = (n) => {
  let url = `https://jsonplaceholder.typicode.com/posts/${n}`
  return fetch(url)
    .then(resp => resp.json())
    .then(json => ([{ value: json.id, name: `${json.id}` }]))
}

inquirer.prompt({
  type: 'lazy-list',
  name: 'posts',
  message: 'Inbox',
  pageSize: pageSize,
  choices: new Array(5).fill(0).map((_, i) => ({ value: i, name: i })),
  onChange: (state, eventType) => {
    let index = state.selected
    let listLength = state.opt.choices.length
    let shouldFetchMore = (index + pageSize) > listLength
    if (
      eventType === 'onDownKey' &&
      shouldFetchMore
    ) {
      return fetchMore(state.opt.choices.length)
        .then(choices => {
          return state.opt.choices.choices.concat(choices)
        })
    }
  }
})