'use strict';

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

var _regenerator;

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

var _bluebird;

function _load_bluebird() {
  return _bluebird = require('bluebird');
}

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 _path;

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

var _fsExtra;

function _load_fsExtra() {
  return _fsExtra = _interopRequireDefault(require('fs-extra'));
}

var _glob;

function _load_glob() {
  return _glob = _interopRequireDefault(require('glob'));
}

var _ramda;

function _load_ramda() {
  return _ramda = _interopRequireDefault(require('ramda'));
}

var _diagnosis;

function _load_diagnosis() {
  return _diagnosis = _interopRequireDefault(require('../diagnosis'));
}

var _consumer;

function _load_consumer() {
  return _consumer = require('../../consumer');
}

var _scope;

function _load_scope() {
  return _scope = require('../../scope');
}

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

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var DIAGNOSIS_NAME = exports.DIAGNOSIS_NAME = 'check environment symlinks';

var BrokenSymlinkFiles = function (_Diagnosis) {
  _inherits(BrokenSymlinkFiles, _Diagnosis);

  function BrokenSymlinkFiles() {
    var _ref;

    var _temp, _this, _ret;

    _classCallCheck(this, BrokenSymlinkFiles);

    for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = BrokenSymlinkFiles.__proto__ || Object.getPrototypeOf(BrokenSymlinkFiles)).call.apply(_ref, [this].concat(args))), _this), _this.name = DIAGNOSIS_NAME, _this.description = 'validate generated symlinks for workspace environments', _this.category = 'local environments', _temp), _possibleConstructorReturn(_this, _ret);
  }

  _createClass(BrokenSymlinkFiles, [{
    key: '_formatSymptoms',
    value: function _formatSymptoms(bareResult) {
      if (!bareResult.data) throw new Error('BrokenSymlinkFiles, bareResult.data is missing');
      var toString = bareResult.data.brokenSymlinks.map(function (brokenSymlink) {
        return `symlink path: "${brokenSymlink.symlinkPath}", broken link: "${brokenSymlink.brokenPath}"`;
      }).join('\n');
      return `the following symlinks points to non-existing paths\n${toString}`;
    }
  }, {
    key: '_formatManualTreat',
    value: function _formatManualTreat(bareResult) {
      if (!bareResult.data) throw new Error('BrokenSymlinkFiles, bareResult.data is missing');
      var toString = (_ramda || _load_ramda()).default.uniq(bareResult.data.brokenSymlinks.map(function (b) {
        return b.pathToDelete;
      })).join('\n');
      return `please delete the following paths:\n${toString}`;
    }
  }, {
    key: '_runExamine',
    value: function () {
      var _ref2 = (0, (_bluebird || _load_bluebird()).coroutine)( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee2() {
        var _this2 = this;

        var consumer, envComponentsDir, potentialSymlinks, potentialSymlinksAbs, brokenSymlinks, results;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee2$(_context2) {
          while (1) {
            switch (_context2.prev = _context2.next) {
              case 0:
                _context2.next = 2;
                return (0, (_consumer || _load_consumer()).loadConsumer)();

              case 2:
                consumer = _context2.sent;
                envComponentsDir = (_path || _load_path()).default.join(consumer.scope.getPath(), (_scope || _load_scope()).Scope.getComponentsRelativePath());
                potentialSymlinks = (_glob || _load_glob()).default.sync('**/node_modules/@bit/**', { cwd: envComponentsDir });
                potentialSymlinksAbs = potentialSymlinks.map(function (p) {
                  return (_path || _load_path()).default.join(envComponentsDir, p);
                });
                brokenSymlinks = [];
                results = potentialSymlinksAbs.map(function () {
                  var _ref3 = (0, (_bluebird || _load_bluebird()).coroutine)( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee(potentialSymlink) {
                    var link, exists, brokenSymlink;
                    return (_regenerator || _load_regenerator()).default.wrap(function _callee$(_context) {
                      while (1) {
                        switch (_context.prev = _context.next) {
                          case 0:
                            _context.next = 2;
                            return _this2._getLinkIfExist(potentialSymlink);

                          case 2:
                            link = _context.sent;

                            if (link) {
                              _context.next = 5;
                              break;
                            }

                            return _context.abrupt('return');

                          case 5:
                            _context.next = 7;
                            return (_fsExtra || _load_fsExtra()).default.exists(link);

                          case 7:
                            exists = _context.sent;

                            if (!exists) {
                              _context.next = 10;
                              break;
                            }

                            return _context.abrupt('return');

                          case 10:
                            brokenSymlink = {
                              symlinkPath: potentialSymlink,
                              brokenPath: link,
                              pathToDelete: _this2._getPathToDelete(potentialSymlink)
                            };

                            brokenSymlinks.push(brokenSymlink);

                          case 12:
                          case 'end':
                            return _context.stop();
                        }
                      }
                    }, _callee, _this2);
                  }));

                  return function (_x) {
                    return _ref3.apply(this, arguments);
                  };
                }());
                _context2.next = 10;
                return Promise.all(results);

              case 10:
                return _context2.abrupt('return', {
                  valid: brokenSymlinks.length === 0,
                  data: {
                    brokenSymlinks
                  }
                });

              case 11:
              case 'end':
                return _context2.stop();
            }
          }
        }, _callee2, this);
      }));

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

      return _runExamine;
    }()
  }, {
    key: '_getLinkIfExist',
    value: function () {
      var _ref4 = (0, (_bluebird || _load_bluebird()).coroutine)( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee3(symlinkPath) {
        var link;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee3$(_context3) {
          while (1) {
            switch (_context3.prev = _context3.next) {
              case 0:
                _context3.prev = 0;
                _context3.next = 3;
                return (_fsExtra || _load_fsExtra()).default.readlink(symlinkPath);

              case 3:
                link = _context3.sent;
                return _context3.abrupt('return', link);

              case 7:
                _context3.prev = 7;
                _context3.t0 = _context3['catch'](0);
                return _context3.abrupt('return', null);

              case 10:
              case 'end':
                return _context3.stop();
            }
          }
        }, _callee3, this, [[0, 7]]);
      }));

      function _getLinkIfExist(_x2) {
        return _ref4.apply(this, arguments);
      }

      return _getLinkIfExist;
    }()

    /**
     * deleting the environment directory causes Bit to reinstall it next time
     */

  }, {
    key: '_getPathToDelete',
    value: function _getPathToDelete(symlinkPath) {
      var envDirectory = symlinkPath.split((_path || _load_path()).default.join('node_modules', '@bit'))[0];
      return envDirectory.slice(0, -1); // remove the last slash
    }
  }]);

  return BrokenSymlinkFiles;
}((_diagnosis || _load_diagnosis()).default);

exports.default = BrokenSymlinkFiles;