const LazyList = require('inquirer/lib/prompts/list')
const Choices = require('inquirer/lib/objects/choices')

LazyList.prototype.fetchMore = async function (type) {
  if (typeof this.opt.onChange === 'function') {
    let choices = await this.opt.onChange(this, type)
    if (choices) {
      if (!Array.isArray(choices)) {
        choices = [choices]
      }
      this.opt.choices = new Choices(choices, this.answers)
      return Promise.resolve(true)
    }
  }
  return Promise.resolve(false)
}

LazyList.prototype.onUpKey = async function () {
  if (this._promise) await this._promise
  var len = this.opt.choices.realLength
  this.selected = this.selected > 0 ? this.selected - 1 : len - 1
  this._promise = this.fetchMore('onUpKey')
  this.render()
}

LazyList.prototype.onDownKey = async function () {
  if (this._promise) await this._promise
  var len = this.opt.choices.realLength
  this.selected = this.selected < len - 1 ? this.selected + 1 : 0
  this._promise = this.fetchMore('onDownKey')
  this.render()
}

module.exports = LazyList
