#!/usr/bin/env node

const { EOL } = require('os')
const minimist = require('minimist')
const { Transform } = require('stream');
const fs = require('fs')
const csv = require('../')
const pkg = require('../package.json')

const argv = minimist(process.argv, {
  alias: {
    c: 'skipComments',
    e: 'escape',
    h: 'headers',
    o: 'output',
    q: 'quote',
    l: 'skipLines',
    s: 'separator',
    v: 'version'
  },
  default: {
    e: '"',
    q: '"',
    s: ','
  },
  boolean: ['version', 'help']
})

const [,, filename] = argv._

if (argv.version) {
  console.log(pkg.version)
  process.exit(0)
}

if (argv.help || (process.stdin.isTTY && !filename)) {
  console.error(`Usage: csv-parser [filename?] [options]
  --escape,-e         Set the escape character (defaults to quote value)
  --headers,-h        Explicitly specify csv headers as a comma separated list
  --help              Show this help
  --output,-o         Set output file. Defaults to stdout
  --quote,-q          Set the quote character ('"' by default)
  --remove            Remove headers from output
  --separator,-s      Set the separator character ("," by default)
  --skipComments,-c   Skip CSV comments that begin with '#'. Set a value to change the comment character.
  --skipLines,-l      Set the number of lines to skip to before parsing headers
  --strict            Require column length match headers length
  --version,-v        Print out the installed version
`)
  process.exit(1)
}

let input
const output = (argv.output && argv.output !== '-') ? fs.createWriteStream(argv.output) : process.stdout
const options = {
  separator: argv.separator,
  strict: argv.strict,
  skipComments: argv.skipComments,
  skipLines: argv.skipLines
}

if (argv.headers) {
  options.headers = argv.headers.toString().split(argv.separator)
}

if (argv.remove) {
  const removeHeaders = argv.remove.split(',')
  options.mapHeaders = (name, i) => {
    return removeHeaders.indexOf(name) === -1 ? name : null
  }
}

if (filename === '-' || !filename) {
  input = process.stdin
} else if (fs.existsSync(filename)) {
  input = fs.createReadStream(filename)
} else {
  console.error(`File: ${filename} does not exist`)
  process.exit(2)
}

const serialize = () => {
  return new Transform({
    objectMode: true,
    transform(obj, enc, cb) {
      cb(null, JSON.stringify(obj) + EOL)
    }
  });
}

input
  .pipe(csv(options))
  .pipe(serialize())
  .pipe(output)
