var pathExists = require('path-exists');
var mkdir = require('mkdirp');
var path = require('path');
var fs = require('fs');
var appDir = path.join(require('home-path')(), './.pubuim');
var appConfigFile = path.resolve(appDir, 'config.json')

exports.get = function (cb) {
  pathExists(appConfigFile, function (err, exists) {
    if (err) return cb(err);

    if (!exists) return cb(null, null);

    try {
      var content = fs.readFileSync(appConfigFile);
      return cb(null, JSON.parse(content));
    } catch (e) {
      return cb(e);
    }
  })
};

exports.set = function (json, cb) {
  pathExists(appConfigFile, function (err, exists) {
    if (err) return cb && cb(err);

    function writeConfig() {
      try {
        fs.writeFileSync(appConfigFile, JSON.stringify(json));
        return cb && cb(null, true)
      } catch (e) {
        return cb && cb(e);
      }
    }

    if (exists) {
      writeConfig();
    } else {
      mkdir(appDir, function (err) {
        if (err) return cb && cb(err);
        writeConfig();
      })
    }
  })
};
