'use strict';

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

var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();

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

function _load_decamelize() {
  return _decamelize = _interopRequireDefault(require('decamelize'));
}

var _ramda;

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

var _version;

function _load_version() {
  return _version = _interopRequireDefault(require('../version'));
}

var _exceptions;

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

var _constants;

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

var _utils;

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

var _generalError;

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

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 BitId = function () {
  function BitId(_ref) {
    var scope = _ref.scope,
        box = _ref.box,
        name = _ref.name,
        version = _ref.version;

    _classCallCheck(this, BitId);

    this.scope = scope || null;
    this.box = box || 'global';
    this.name = name;
    this.version = version || null;
  }

  _createClass(BitId, [{
    key: 'clone',
    value: function clone() {
      return new BitId(this);
    }
  }, {
    key: 'changeScope',
    value: function changeScope(newScope) {
      return new BitId({ scope: newScope, box: this.box, name: this.name, version: this.version });
    }
  }, {
    key: 'isLocal',
    value: function isLocal(scopeName) {
      return !this.scope || scopeName === this.scope;
    }
  }, {
    key: 'getVersion',
    value: function getVersion() {
      return (_version || _load_version()).default.parse(this.version);
    }
  }, {
    key: 'hasVersion',
    value: function hasVersion() {
      return this.version && this.version !== (_constants || _load_constants()).LATEST_BIT_VERSION;
    }
  }, {
    key: 'toString',
    value: function toString() {
      var ignoreScope = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
      var ignoreVersion = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
      var name = this.name,
          box = this.box,
          version = this.version;

      var scope = this.scope;
      var componentStr = ignoreScope || !scope ? [box, name].join('/') : [scope, box, name].join('/');
      // when there is no scope and the version is latest, omit the version.
      if (ignoreVersion || !this.hasVersion()) return componentStr;
      // $FlowFixMe version here is a string because this.hasVersion() is true
      return componentStr.concat(`${(_constants || _load_constants()).VERSION_DELIMITER}${version}`);
    }
  }, {
    key: 'toStringWithoutScope',
    value: function toStringWithoutScope() {
      return this.toString(true);
    }
  }, {
    key: 'toStringWithoutVersion',
    value: function toStringWithoutVersion() {
      return this.toString(false, true);
    }
  }, {
    key: 'toStringWithoutScopeAndVersion',
    value: function toStringWithoutScopeAndVersion() {
      return this.toString(true, true);
    }
  }, {
    key: 'toObject',
    value: function toObject() {
      var key = this.scope ? [this.scope, this.box, this.name].join('/') : [this.box, this.name].join('/');
      var value = this.version;

      return { [key]: value };
    }
  }, {
    key: 'toFullPath',
    value: function toFullPath() {
      return (_path || _load_path()).default.join(this.box, this.name, this.scope, this.version);
    }

    /**
     * Get a string id and return a string without the version part
     * @param {string} id
     * @return {string} id - id without version
     */

  }], [{
    key: 'getStringWithoutVersion',
    value: function getStringWithoutVersion(id) {
      return id.split((_constants || _load_constants()).VERSION_DELIMITER)[0];
    }
  }, {
    key: 'getVersionOnlyFromString',
    value: function getVersionOnlyFromString(id) {
      return id.split((_constants || _load_constants()).VERSION_DELIMITER)[1];
    }
  }, {
    key: 'parse',
    value: function parse(id) {
      var version = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : (_constants || _load_constants()).LATEST_BIT_VERSION;

      if (!id || id === (_constants || _load_constants()).NO_PLUGIN_TYPE) {
        return null;
      }
      if (id.includes((_constants || _load_constants()).VERSION_DELIMITER)) {
        var _id$split = id.split((_constants || _load_constants()).VERSION_DELIMITER),
            _id$split2 = _slicedToArray(_id$split, 2),
            newId = _id$split2[0],
            newVersion = _id$split2[1];

        id = newId;
        version = newVersion;
      }

      var idSplit = id.split('/');
      if (idSplit.length === 3) {
        var _idSplit = _slicedToArray(idSplit, 3),
            _scope = _idSplit[0],
            _box = _idSplit[1],
            _name = _idSplit[2];

        if (!(0, (_utils || _load_utils()).isValidIdChunk)(_name) || !(0, (_utils || _load_utils()).isValidIdChunk)(_box) || !(0, (_utils || _load_utils()).isValidScopeName)(_scope)) {
          // $FlowFixMe
          throw new (_exceptions || _load_exceptions()).InvalidIdChunk(`${_scope}/${_box}/${_name}`);
        }
        // $FlowFixMe (in this case the realScopeName is not null)
        return new BitId({
          scope: _scope,
          box: _box,
          name: _name,
          version
        });
      }

      if (idSplit.length === 2) {
        var _idSplit2 = _slicedToArray(idSplit, 2),
            _box2 = _idSplit2[0],
            _name2 = _idSplit2[1];

        if (!(0, (_utils || _load_utils()).isValidIdChunk)(_name2) || !(0, (_utils || _load_utils()).isValidIdChunk)(_box2)) {
          // $FlowFixMe
          throw new (_exceptions || _load_exceptions()).InvalidIdChunk(`${_box2}/${_name2}`);
        }
        // $FlowFixMe
        return new BitId({
          box: _box2,
          name: _name2,
          version
        });
      }

      if (idSplit.length === 1) {
        var _idSplit3 = _slicedToArray(idSplit, 1),
            _name3 = _idSplit3[0];

        if (!(0, (_utils || _load_utils()).isValidIdChunk)(_name3)) {
          // $FlowFixMe
          throw new (_exceptions || _load_exceptions()).InvalidIdChunk(_name3);
        }
        // $FlowFixMe
        return new BitId({
          name: _name3,
          version
        });
      }

      throw new (_exceptions || _load_exceptions()).InvalidBitId();
    }
  }, {
    key: 'getValidScopeName',
    value: function getValidScopeName(scope) {
      var suggestedName = scope.toLowerCase();
      var cleanName = suggestedName.split('').map(function (char) {
        if (/^[$\-_!.a-z0-9]+$/.test(char)) return char;
        return '';
      }).join('');

      // allow only one dot
      var nameSplitByDot = cleanName.split('.');
      if (nameSplitByDot.length > 1) {
        cleanName = `${(_ramda || _load_ramda()).default.head(nameSplitByDot)}.${(_ramda || _load_ramda()).default.tail(nameSplitByDot).join('')}`;
      }

      if (!cleanName) {
        throw new (_generalError || _load_generalError()).default('scope name created by directory name have to contains at least one character or number');
      }
      return cleanName;
    }
  }, {
    key: 'getValidBitId',
    value: function getValidBitId(box, name) {
      var getValidIdChunk = function getValidIdChunk(chunk) {
        if (!(0, (_utils || _load_utils()).isValidIdChunk)(chunk)) {
          chunk = chunk.replace(/\./g, '');
          chunk = (0, (_decamelize || _load_decamelize()).default)(chunk, '-');
        }
        return chunk;
      };

      return new BitId({ name: getValidIdChunk(name), box: getValidIdChunk(box) });
    }
  }]);

  return BitId;
}();

exports.default = BitId;