module Node

import Prelude

pfunc getArgs uses (arrayToList MkIORes) :  IO (List String) := `(w) => Prelude_MkIORes(null, Prelude_arrayToList(null, process.argv.slice(1)), w)`
pfunc readFile uses (MkIORes Left Right) : (fn : String) -> IO (Either String String) := `(fn) => (w) => {
  let fs = require('fs')
  let result
  try {
    let content = fs.readFileSync(fn, 'utf8')
    result = Prelude_Right(null, null, content)
  } catch (e) {
    let err = ""+e
    result = Prelude_Left(null, null, e)
  }
  return Prelude_MkIORes(null, result, w)
}`

-- I wonder if I should automatically `uses` the constructors in the types
pfunc writeFile uses (MkIORes MkUnit) : String → String → IO (Either String Unit) := `(fn, content) => (w) => {
  let fs = require('fs')
  let result
  try {
    fs.writeFileSync(fn, content, 'utf8')
    result = Prelude_Right(null, null, Prelude_MkUnit)
  } catch (e) {
      let err = ""+e
      result = Prelude_Left(null, null, e)
  }
  return Prelude_MkIORes(null, result, w)
}`

-- maybe System.exit or something, like the original putStrLn msg >> exitFailure
pfunc exitFailure : ∀ a. String → a := `(_, msg) => {
  console.log(msg);
  process.exit(1);
}`

