const fs = require('fs')
const path = require('path')
const {home} = require('osenv')

const authPath = path.join(home(), ".wm-auth.json");

const host2fname = host => host.replace(/[^\w-]+/ig, ".");

// .block-auth.json => {username, host, token}
// block.http.localhost.3000.json => {id, entrypoint}
// block.https.weblium.com.json => {id, entrypoint}
// block.https.weblium.io.json => {id, entrypoint}
//

const read = fname => {
  try {
    return JSON.parse(fs.readFileSync(fname, 'utf8'))
  } catch (e) {
    // noop
  }
  return null
}

const unlink = fname => {
  try {
    fs.unlinkSync(fname)
  } catch(e) {
    // noop
  }
}

const write = (fname, data) => fs.writeFileSync(fname, JSON.stringify(data, null, 2)+"\n");

module.exports = {
  host2fname,
  auth: {
    read: () => read(authPath),
    write: data => write(authPath, data),
    drop: () => unlink(authPath),
    host() {
      const conf = read(authPath)
      return conf && conf.host || "http://localhost:3000"
    }
  },
  host: (prefix) => ({
    read: (host, customLocation = '') => read(path.join(customLocation, prefix+"."+host2fname(host))),
    write: (host, data, customLocation) => write(path.join(customLocation, prefix+"."+host2fname(host)), data),
    unlink: (host, customLocation) => unlink(path.join(customLocation, prefix+"."+host2fname(host))),
  })
}
