let fs = require('fs')
let path = require('path')
let tildify = require('tildify')
let mkdirp = require('mkdirp')
let common = require('../common')
let conf = require('../conf')

module.exports = {
  add,
  rm,
  ls
}

let serversDir = common.serversDir

mkdirp.sync(serversDir)

function getId (name) {
  return name || path.basename(process.cwd())
}

function getServerFile (id) {
  return `${serversDir}/${id}.json`
}

function add (cmd, opts) {
  let id = getId(opts.n)
  let file = getServerFile(id)
  let obj = {
    cwd: process.cwd(),
    cmd: cmd
  }

  if (opts.o) obj.out = opts.o

  obj.env = {}

  // By default, save PATH env for version managers users
  obj.env.PATH = process.env.PATH

  if (opts.e && process.env[opts.e]) {
    obj.env[opts.e] = process.env[opts.e]
  }

  let data = JSON.stringify(obj, null, 2)

  console.log(`  Create ${tildify(file)}`)
  fs.writeFileSync(file, data)

  console.log(`  Added  http://localhost:${conf.port}/${id}`)

  if (!obj.out) {
    console.log(`  Warn   No log file specified. Output will be discarded.`)
    console.log(`         Use '-o log.txt' to specify a logfile.`)
  }
}

function rm (name) {
  let id = getId(name)
  let file = getServerFile(id)

  console.log(`  Remove  ${tildify(file)}`)
  console.log(`  Removed`)

  fs.unlink(file, function () {})
}

function ls () {
  let list = fs
    .readdirSync(serversDir)
    .map(file => {
      let id = path.basename(file, '.json')
      let serverFile = getServerFile(id)
      let server = JSON.parse(fs.readFileSync(serverFile))
      return `  ${tildify(server.cwd)}$ ${server.cmd}\n` +
        `  http://localhost:${conf.port}/${id}`
    })
    .join('\n\n')

  console.log(list)
}

@@ -905,84 +905,119 @@
 %0A%0A  
-console.log(%60  Added  http://localhost:$%7Bconf.port%7D/$%7Bid
+if (obj.out) %7B%0A    let logFile = tildify(path.resolve(obj.out))%0A    console.log(%60  Output $%7BlogFile
 %7D%60)%0A
-%0A
   
-if (!obj.out)
+%7D else
  %7B%0A 
@@ -1035,17 +1035,17 @@
 log(
-%60  Warn  
+'  Output
  No 
@@ -1066,40 +1066,37 @@
 fied
-. Output will be discarded.%60
+ (use %5C'-o app.log%5C')'
 )%0A  
+%7D%0A%0A
   co
@@ -1112,59 +1112,52 @@
 (%60  
-       Use '-o log.txt' to specify a logfile.%60)%0A  %7D
+Added  http://localhost:$%7Bconf.port%7D/$%7Bid%7D%60)
 %0A%7D%0A%0A

Update add message