'use strict';

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

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

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

var _fsExtra2 = _interopRequireDefault(_fsExtra);

var _mkdirp = require('mkdirp');

var _mkdirp2 = _interopRequireDefault(_mkdirp);

var _path = require('path');

var _path2 = _interopRequireDefault(_path);

var _cli = require('../../cli');

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

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var singleton = Symbol();
var singletonEnforcer = Symbol();

var Manager = function () {
  function Manager(enforcer) {
    _classCallCheck(this, Manager);

    if (enforcer != singletonEnforcer) throw 'Cannot construct Json singleton';

    this._isEnable = _cli.config.users.enable;
    this._file = _path2.default.join(_cli.config.root, 'users', 'bdd.json');
  }

  _createClass(Manager, [{
    key: 'read',
    value: function read() {
      if (this._isEnable) {
        if (_cli.coreUtils.file.exist(this._file)) {
          return JSON.parse(_fsExtra2.default.readFileSync(this._file, 'utf8'));
        } else {
          this._users = [];
          var admin = _cli.User.operations.add(_cli.config.users.default);
          this.save();
          _cli.User.operations.activate(admin.user.id);
          return JSON.parse(_fsExtra2.default.readFileSync(this._file, 'utf8'));
        }
      }
      return [];
    }
  }, {
    key: 'save',
    value: function save() {
      if (this._isEnable) {
        (0, _mkdirp2.default)(_path2.default.dirname(this._file));
        _fsExtra2.default.writeJsonSync(this._file, this._users, { space: 2, encoding: 'utf-8' });
      }
    }
  }, {
    key: 'get',
    value: function get() {
      if (this._users == null) {
        this._users = this.read();
      }
      return this._users;
    }
  }, {
    key: 'update',
    value: function update(json) {
      if (this._isEnable) {
        this._users = json;
        this.save();
        return true;
      }
      return false;
    }
  }], [{
    key: 'instance',
    get: function get() {
      if (!this[singleton]) {
        this[singleton] = new Manager(singletonEnforcer);
      }
      return this[singleton];
    }
  }]);

  return Manager;
}();

exports.default = Manager;