/**
 * @function apemanask
 * @param {string} question - Question to ask.
 * @param {object} options - Optional settings.
 * @returns {Promise}
 */
'use strict'

const readline = require('readline')
const co = require('co')

/** @lends apemanask */
function apemanask (question, options = {}) {
  let rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
  })
  let { suffix } = options
  return co(function * () {
    return yield new Promise((resolve, reject) =>
      rl.question(question + (suffix || ''), (answer) => {
        rl.close()
        process.nextTick(() => {
          resolve(answer)
        })
      })
    )
  })
}

/**
 * As yes no.
 * @param {string} question - Question to ask.
 * @param {object} options - Optional settings.
 * @returns {Promise}
 */
apemanask.yesno = function (question, options = {}) {
  return co(function * () {
    let answer = yield apemanask(question, Object.assign({
      suffix: '[y/N]'
    }, options))
    answer = String(answer).toLocaleLowerCase().trim()
    return answer === 'y' || answer === 'yes'
  })
}

module.exports = apemanask
