plugins/ConfigPlugin.js

const ConfigStore = require('configstore')

function configDir(configPath) {
  const pths = configPath.split('/')
  pths.pop()
  const configDirStr = pths.join('/')
  return configDirStr
}

/**
 * @param  {ObjChain} chain
 * @param  {string} [name]
 */
function configPlugin(chain, name) {
  const config = new ConfigStore(name || chain.pkg.name)
  chain.config = config

  chain.clear = config.clear
  chain.size = config.size
  chain.path = config.path
  chain.data = config.all
  chain.configDir = () => configDir(config.path)

  // putting these as middleware instead
  // chain.get = config.get
  // chain.update = config.update
  // chain.has = config.has
  // chain.del = config.delete
  // chain.delete = config.delete
  // chain.set = config.set

  // https://github.com/rauschma/openurl/blob/master/openurl.js
  // open(config.path)

  const configMiddleware = {
    set(key, val) {
      config.set(key, val)
    },
    save() {
      // require('fliplog').quick('saving', config, config.all)
      // trigger getter and setter
      const all = config.all
      config.all = all
    },
    get(key) {
      return config.get(key)
    },
    delete(key) {
      return config.delete(key)
    },
    has(key) {
      return config.has(key)
    },
  }

  chain.use({
    middleware: configMiddleware,
    configName(newName) {
      return configPlugin(this, newName)
    },
  })
}

const ConfigPlugin = configPlugin

module.exports = ConfigPlugin