var fs = require('fs')
const readline = require('readline')
const { once } = require('events')
var exec = require('child_process').exec

function bufferFile(path) {
  try {
    return fs.readFileSync(path, { encoding: 'utf8' })
  } catch (e) {
    return ''
  }
}

async function head (path, lines) {
  let x = 0
  let acc = []
  const readInterface = readline.createInterface({
    input: fs.createReadStream(path),
    terminal: false,
    crlfDelay: Infinity
  })
  readInterface.on('line', function(line) {
    acc.push(line)
    x++
    if (lines && x >= lines) {
      readInterface.close()
      readInterface.removeAllListeners()
    }
  })
  await once(readInterface, 'close')
  return acc
}

function wc (path) {
  return new Promise((resolve, reject) => {
    exec("sed -n '$=' " + path, function (error, results) {
      if (error) {
        reject(error)
      } else {
        resolve(results.toString().trim())
      }
    })
  })
}

function escape (text) {
  return text.replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;').replace('"', '&quot;').replace("'", '&#x27;')
}

module.exports = {
  bufferFile: bufferFile,
  head: head,
  wc: wc,
  escape: escape
}
