// @nanoapp/nstd
// -----------------------------------------------------------------------------
// Shell
import { Command, CommandReq } from './lib/shell'
export { Command, CommandReq }
export function Exec(cmd, callback, onError) {
  if (!callback) callback = console.log
  if (!onError) onError = console.error

  let req
  if (typeof cmd === "string") {
    req = new CommandReq()
    let args = cmd.split(" ")
    req.setProg(args[0])
    req.setArgsList(args.slice(1, ))
  } else if (cmd instanceof CommandReq) {
    req = cmd
  } else {
    throw "cmd arugment only support CommandReq object or string"
  }

  let control = {}
  let p = (new Command).Exec(req, (msg) => {
    let err = msg.getError()
    if (err) {
      onError(err)
    } else {
      callback(msg.getOutput())
    }
  }, control)

  p.kill = control.cancel

  return p
}
