"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;

function _bluebird() {
  const data = require("bluebird");

  _bluebird = function () {
    return data;
  };

  return data;
}

function _path() {
  const data = _interopRequireDefault(require("path"));

  _path = function () {
    return data;
  };

  return data;
}

function _fsExtra() {
  const data = _interopRequireDefault(require("fs-extra"));

  _fsExtra = function () {
    return data;
  };

  return data;
}

function _constants() {
  const data = require("../constants");

  _constants = function () {
    return data;
  };

  return data;
}

function _utils() {
  const data = require("../utils");

  _utils = function () {
    return data;
  };

  return data;
}

function getPath() {
  return _path().default.join(_constants().GLOBAL_CONFIG, _constants().GLOBAL_CONFIG_FILE);
}

class Config extends Map {
  toPlainObject() {
    return (0, _utils().mapToObject)(this);
  }

  toJson() {
    return JSON.stringify(this.toPlainObject());
  }

  write() {
    return _fsExtra().default.outputFile(getPath(), this.toJson());
  }

  writeSync() {
    return _fsExtra().default.outputFileSync(getPath(), this.toJson());
  }

  static loadSync() {
    try {
      const configPath = getPath();

      if (!_fsExtra().default.existsSync(configPath)) {
        const config = new Config([]);
        config.writeSync();
        return config;
      }

      const contents = _fsExtra().default.readFileSync(configPath);

      return new Config((0, _utils().objectToTupleArray)(JSON.parse(contents.toString())));
    } catch (err) {
      return err;
    }
  }

  static load() {
    return (0, _bluebird().coroutine)(function* () {
      try {
        const configPath = getPath();
        const exists = yield _fsExtra().default.exists(configPath);

        if (!exists) {
          const config = new Config([]);
          yield config.write();
          return config;
        }

        const contents = yield _fsExtra().default.readFile(configPath);
        return new Config((0, _utils().objectToTupleArray)(JSON.parse(contents.toString())));
      } catch (err) {
        return err;
      }
    })();
  }

}

exports.default = Config;