"use strict";

exports.__esModule = true;
exports.default = void 0;

var _lodash = require("lodash");

var _events = _interopRequireDefault(require("events"));

var _cson = _interopRequireDefault(require("cson"));

var _fsExtra = _interopRequireDefault(require("fs-extra"));

var _pathExtra = _interopRequireDefault(require("path-extra"));

var _debug = _interopRequireDefault(require("./debug"));

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

const {
  ROOT,
  EXROOT
} = global;

const defaultConfigPath = _pathExtra.default.join(ROOT, 'config.cson');

const configPath = _pathExtra.default.join(EXROOT, 'config.cson');

class configClass extends _events.default {
  constructor() {
    super();
    this.configData = null;

    try {
      _fsExtra.default.accessSync(configPath, _fsExtra.default.R_OK | _fsExtra.default.W_OK);

      this.configData = _cson.default.parseCSONFile(configPath);

      _debug.default.log(`Config loaded from: ${configPath}`);
    } catch (e) {
      _debug.default.log(e);
    }

    if (!this.configData) {
      try {
        _fsExtra.default.accessSync(defaultConfigPath, _fsExtra.default.R_OK);

        this.configData = _cson.default.parseCSONFile(defaultConfigPath) || {};

        _debug.default.log(`Config loaded from: ${defaultConfigPath}`);
      } catch (e) {
        this.configData = {};

        _debug.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 {
        _fsExtra.default.writeFileSync(configPath, _cson.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);
var _default = config;
exports.default = _default;
module.exports = exports["default"];