'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _lodash = require('lodash');

var _events = require('events');

var _events2 = _interopRequireDefault(_events);

var _cson = require('cson');

var _cson2 = _interopRequireDefault(_cson);

var _fsExtra = require('fs-extra');

var _fsExtra2 = _interopRequireDefault(_fsExtra);

var _pathExtra = require('path-extra');

var _pathExtra2 = _interopRequireDefault(_pathExtra);

var _debug = require('./debug');

var _debug2 = _interopRequireDefault(_debug);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

const { ROOT, EXROOT } = global;
const defaultConfigPath = _pathExtra2.default.join(ROOT, 'config.cson');
const configPath = _pathExtra2.default.join(EXROOT, 'config.cson');

class configClass extends _events2.default {
  constructor() {
    super();
    this.configData = null;
    try {
      _fsExtra2.default.accessSync(configPath, _fsExtra2.default.R_OK | _fsExtra2.default.W_OK);
      this.configData = _cson2.default.parseCSONFile(configPath);
      _debug2.default.log`Config loaded from: ${configPath}`;
    } catch (e) {
      _debug2.default.log(e);
    }
    if (!this.configData) {
      try {
        _fsExtra2.default.accessSync(defaultConfigPath, _fsExtra2.default.R_OK);
        this.configData = _cson2.default.parseCSONFile(defaultConfigPath) || {};
        _debug2.default.log`Config loaded from: ${defaultConfigPath}`;
      } catch (e) {
        this.configData = {};
        _debug2.default.log(e);
      }
    }
    this.get = (path, value) => {
      if (path === '') {
        return this.configData;
      }
      const ret = (0, _lodash.get)(this.configData, path);
      if (ret !== undefined) {
        return ret;
      } else {
        return value;
      }
    };
    this.set = (path, value) => {
      if ((0, _lodash.get)(this.configData, path) === value) {
        return;
      }
      (0, _lodash.set)(this.configData, path, value);
      this.emit('config.set', path, value);
      try {
        _fsExtra2.default.writeFileSync(configPath, _cson2.default.stringify(this.configData, null, 2));
      } catch (e) {
        console.warn(e);
      }
    };
    this.setDefault = (path, value) => {
      if (this.get(path) === undefined) {
        this.set(path, value);
      }
    };
  }
}

const config = new configClass();
config.setMaxListeners(100);

exports.default = config;
module.exports = exports['default'];