import { readFileSync, createReadStream } from 'node:fs';
import readline from 'readline'
import { once } from 'events'
import { exec } from 'node:child_process'

export function bufferFile (path) {
  try {
    return readFileSync(path, { encoding: 'utf8' })
  } catch (_e) {
    return ''
  }
}

export async function head (path, lines) {
  let x = 0
  const acc = []
  const readInterface = readline.createInterface({
    input: 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
}

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

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