"use strict";

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

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.add = add;
exports.remove = remove;
exports.list = list;
exports.refresh = refresh;

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

  _bluebird = function () {
    return data;
  };

  return data;
}

function _scope() {
  const data = require("../../../scope");

  _scope = function () {
    return data;
  };

  return data;
}

function _remotes() {
  const data = require("../../../remotes");

  _remotes = function () {
    return data;
  };

  return data;
}

function _globalConfig() {
  const data = require("../../../global-config");

  _globalConfig = function () {
    return data;
  };

  return data;
}

function _scopeRemotes() {
  const data = require("../../../scope/scope-remotes");

  _scopeRemotes = function () {
    return data;
  };

  return data;
}

function _generalError() {
  const data = _interopRequireDefault(require("../../../error/general-error"));

  _generalError = function () {
    return data;
  };

  return data;
}

function buildRemote(url) {
  return new (_remotes().Remote)(url);
}

function add(url, global) {
  const remote = buildRemote(url);
  return remote.scope().then(scopeDesc => {
    remote.name = scopeDesc.name;

    if (global) {
      return _globalConfig().GlobalRemotes.load().then(globalRemotes => {
        return globalRemotes.addRemote(remote).write().then(() => remote);
      });
    }

    return (0, _scope().loadScope)().then(scope => {
      return scope.scopeJson.addRemote(remote).write(scope.getPath()).then(() => remote);
    });
  });
}

function remove(_x, _x2) {
  return _remove.apply(this, arguments);
}

function _remove() {
  _remove = (0, _bluebird().coroutine)(function* (name, global) {
    if (global) {
      const globalRemotes = yield _globalConfig().GlobalRemotes.load();
      const hasRemoved = globalRemotes.rmRemote(name);

      if (!hasRemoved) {
        throw new (_generalError().default)(`remote "${name}" was not found globally, to remove a local remote, please omit the "--global" flag`);
      }

      yield globalRemotes.write();
      return name;
    }

    const scope = yield (0, _scope().loadScope)();
    const hasRemoved = scope.scopeJson.rmRemote(name);

    if (!hasRemoved) {
      throw new (_generalError().default)(`remote "${name}" was not found locally, to remove a global remote, please use "--global" flag`);
    }

    yield scope.scopeJson.write(scope.getPath());
    return name;
  });
  return _remove.apply(this, arguments);
}

function list(global) {
  if (global) {
    return _globalConfig().GlobalRemotes.load().then(globalRemotes => globalRemotes.toPlainObject());
  }

  return (0, _scope().loadScope)().then(scope => {
    return (0, _scopeRemotes().getScopeRemotes)(scope).then(remotes => remotes.toPlainObject());
  });
}

function refresh() {}