'use strict';

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

var _regenerator;

function _load_regenerator() {
  return _regenerator = _interopRequireDefault(require('babel-runtime/regenerator'));
}

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; }; }();

exports.getPath = getPath;

var _path;

function _load_path() {
  return _path = _interopRequireDefault(require('path'));
}

var _utils;

function _load_utils() {
  return _utils = require('../utils');
}

var _remotes;

function _load_remotes() {
  return _remotes = require('../remotes');
}

var _constants;

function _load_constants() {
  return _constants = require('../constants');
}

var _bitId;

function _load_bitId() {
  return _bitId = _interopRequireDefault(require('../bit-id/bit-id'));
}

var _generalError;

function _load_generalError() {
  return _generalError = _interopRequireDefault(require('../error/general-error'));
}

var _exceptions;

function _load_exceptions() {
  return _exceptions = require('./exceptions');
}

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

function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }

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

function getPath(scopePath) {
  return (_path || _load_path()).default.join(scopePath, (_constants || _load_constants()).SCOPE_JSON);
}

var ScopeJson = exports.ScopeJson = function () {
  function ScopeJson(_ref) {
    var name = _ref.name,
        remotes = _ref.remotes,
        resolverPath = _ref.resolverPath,
        license = _ref.license,
        groupName = _ref.groupName,
        version = _ref.version;

    _classCallCheck(this, ScopeJson);

    this.name = name;
    this.version = version;
    this.resolverPath = resolverPath;
    this.license = license;
    this.remotes = remotes || {};
    this.groupName = groupName || '';
  }

  _createClass(ScopeJson, [{
    key: 'toPlainObject',
    value: function toPlainObject() {
      return (0, (_utils || _load_utils()).cleanObject)({
        name: this.name,
        remotes: this.remotes,
        resolverPath: this.resolverPath,
        license: this.license,
        groupName: this.groupName,
        version: this.version
      });
    }
  }, {
    key: 'toJson',
    value: function toJson() {
      var readable = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;

      if (!readable) return JSON.stringify(this.toPlainObject());
      return JSON.stringify(this.toPlainObject(), null, 4);
    }
  }, {
    key: 'set',
    value: function set(key, val) {
      if (!this.hasOwnProperty(key)) throw new (_generalError || _load_generalError()).default(`unknown key ${key}`);
      this[key] = val;
      return this;
    }
  }, {
    key: 'get',
    value: function get(key) {
      if (!this.hasOwnProperty(key)) throw new (_generalError || _load_generalError()).default(`unknown key ${key}`);
      return this[key];
    }
  }, {
    key: 'del',
    value: function del(key) {
      if (!this.hasOwnProperty(key)) throw new (_generalError || _load_generalError()).default(`unknown key ${key}`);
      return this[key];
    }
  }, {
    key: 'addRemote',
    value: function addRemote(remote) {
      this.remotes[remote.name] = remote.host;
      return this;
    }
  }, {
    key: 'rmRemote',
    value: function rmRemote(name) {
      delete this.remotes[name];
      return this;
    }
  }, {
    key: 'write',
    value: function () {
      var _ref2 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee(path) {
        return (_regenerator || _load_regenerator()).default.wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                return _context.abrupt('return', (0, (_utils || _load_utils()).writeFile)((_path || _load_path()).default.join(path, (_constants || _load_constants()).SCOPE_JSON), this.toJson()));

              case 1:
              case 'end':
                return _context.stop();
            }
          }
        }, _callee, this);
      }));

      function write(_x2) {
        return _ref2.apply(this, arguments);
      }

      return write;
    }()
  }, {
    key: 'getPopulatedLicense',
    value: function getPopulatedLicense() {
      if (!this.get('license') || !(0, (_utils || _load_utils()).existsSync)(this.get('license'))) return Promise.resolve();
      return (0, (_utils || _load_utils()).readFile)(this.get('license')).then(function (license) {
        return license.toString();
      });
    }
  }, {
    key: 'name',
    set: function set(suggestedName) {
      this._name = (_bitId || _load_bitId()).default.getValidScopeName(suggestedName);
      return this;
    },
    get: function get() {
      return this._name;
    }
  }], [{
    key: 'loadFromJson',
    value: function loadFromJson(json) {
      return new ScopeJson(JSON.parse(json));
    }
  }, {
    key: 'loadFromFile',
    value: function () {
      var _ref3 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee2(scopeJsonPath) {
        var rawScopeJson;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee2$(_context2) {
          while (1) {
            switch (_context2.prev = _context2.next) {
              case 0:
                rawScopeJson = void 0;
                _context2.prev = 1;
                _context2.next = 4;
                return (0, (_utils || _load_utils()).readFile)(scopeJsonPath);

              case 4:
                rawScopeJson = _context2.sent;
                _context2.next = 12;
                break;

              case 7:
                _context2.prev = 7;
                _context2.t0 = _context2['catch'](1);

                if (!(_context2.t0.code === 'ENOENT')) {
                  _context2.next = 11;
                  break;
                }

                throw new (_exceptions || _load_exceptions()).ScopeJsonNotFound(scopeJsonPath);

              case 11:
                throw _context2.t0;

              case 12:
                return _context2.abrupt('return', ScopeJson.loadFromJson(rawScopeJson.toString()));

              case 13:
              case 'end':
                return _context2.stop();
            }
          }
        }, _callee2, this, [[1, 7]]);
      }));

      function loadFromFile(_x3) {
        return _ref3.apply(this, arguments);
      }

      return loadFromFile;
    }()
  }]);

  return ScopeJson;
}();