'use strict';

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

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

var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };

var _path;

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

var _ramda;

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

var _vinylFile;

function _load_vinylFile() {
  return _vinylFile = _interopRequireDefault(require('vinyl-file'));
}

var _sources;

function _load_sources() {
  return _sources = require('../consumer/component/sources');
}

var _extensionFileNotFound;

function _load_extensionFileNotFound() {
  return _extensionFileNotFound = _interopRequireDefault(require('./exceptions/extension-file-not-found'));
}

var _logger;

function _load_logger() {
  return _logger = _interopRequireDefault(require('../logger/logger'));
}

var _objects;

function _load_objects() {
  return _objects = require('../scope/objects');
}

var _source;

function _load_source() {
  return _source = _interopRequireDefault(require('../scope/models/source'));
}

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 _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 ExtensionFile = function (_AbstractVinyl) {
  _inherits(ExtensionFile, _AbstractVinyl);

  function ExtensionFile() {
    _classCallCheck(this, ExtensionFile);

    return _possibleConstructorReturn(this, (ExtensionFile.__proto__ || Object.getPrototypeOf(ExtensionFile)).apply(this, arguments));
  }

  _createClass(ExtensionFile, [{
    key: 'toModelObject',


    /**
     * Transform an instance of extension file to model object
     * (before storing in the models)
     */
    value: function toModelObject() {
      return {
        name: this.name,
        file: this.file.hash()
      };
    }
  }, {
    key: 'toReadableString',
    value: function toReadableString() {
      return {
        name: this.name,
        content: this.contents.toString()
      };
    }
  }, {
    key: 'clone',
    value: function clone() {
      return new ExtensionFile(this);
    }
  }], [{
    key: 'load',
    value: function () {
      var _ref = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee(name, filePath, consumerPath) {
        var base = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : consumerPath;
        var extendedProps = arguments[4];

        var baseFile, _file, addToFile;

        return (_regenerator || _load_regenerator()).default.wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                _context.prev = 0;
                _context.next = 3;
                return (_vinylFile || _load_vinylFile()).default.read(filePath, { base, cwd: consumerPath });

              case 3:
                baseFile = _context.sent;
                _file = new ExtensionFile(baseFile);

                _file.name = name;
                _file.file = (_source || _load_source()).default.from(_file.contents);

                addToFile = function addToFile(value, key) {
                  return _file[key] = value;
                }; /* eslint-disable-line no-return-assign */


                (_ramda || _load_ramda()).default.forEachObjIndexed(addToFile, extendedProps);
                return _context.abrupt('return', _file);

              case 12:
                _context.prev = 12;
                _context.t0 = _context['catch'](0);

                (_logger || _load_logger()).default.error(`failed loading file ${filePath}. Error: ${_context.t0}`);

                if (!(_context.t0.code === 'ENOENT' && _context.t0.path)) {
                  _context.next = 17;
                  break;
                }

                throw new (_extensionFileNotFound || _load_extensionFileNotFound()).default(_context.t0.path);

              case 17:
                throw _context.t0;

              case 18:
              case 'end':
                return _context.stop();
            }
          }
        }, _callee, this, [[0, 12]]);
      }));

      function load(_x2, _x3, _x4) {
        return _ref.apply(this, arguments);
      }

      return load;
    }()
  }, {
    key: 'loadFromBitJsonObject',
    value: function () {
      var _ref2 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee2(bitJsonObj, consumerPath, bitJsonPath) {
        var _this2 = this;

        var loadP, bitJsonDirPath, loadFile;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee2$(_context2) {
          while (1) {
            switch (_context2.prev = _context2.next) {
              case 0:
                if (!(!bitJsonObj || (_ramda || _load_ramda()).default.isEmpty(bitJsonObj))) {
                  _context2.next = 2;
                  break;
                }

                return _context2.abrupt('return', []);

              case 2:
                loadP = [];
                bitJsonDirPath = (_path || _load_path()).default.dirname(bitJsonPath);

                loadFile = function loadFile(value, key) {
                  // TODO: Gilad - support component bit json
                  var fullPath = (_path || _load_path()).default.resolve(bitJsonDirPath, value);
                  loadP.push(_this2.load(key, fullPath, bitJsonDirPath, consumerPath));
                };

                (_ramda || _load_ramda()).default.forEachObjIndexed(loadFile, bitJsonObj);
                return _context2.abrupt('return', Promise.all(loadP));

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

      function loadFromBitJsonObject(_x5, _x6, _x7) {
        return _ref2.apply(this, arguments);
      }

      return loadFromBitJsonObject;
    }()
  }, {
    key: 'loadFromParsedString',
    value: function loadFromParsedString(parsedString) {
      if (!parsedString) return null;
      var opts = _get(ExtensionFile.__proto__ || Object.getPrototypeOf(ExtensionFile), 'loadFromParsedString', this).call(this, parsedString);
      var extensionFile = new ExtensionFile(opts);
      extensionFile.file = (_source || _load_source()).default.from(extensionFile.contents);
      return extensionFile;
    }
  }, {
    key: 'loadFromParsedStringArray',
    value: function loadFromParsedStringArray(arr) {
      if (!arr) return null;
      return arr.map(this.loadFromParsedString);
    }
  }, {
    key: 'loadFromExtensionFileModel',
    value: function () {
      var _ref3 = _asyncToGenerator( /*#__PURE__*/(_regenerator || _load_regenerator()).default.mark(function _callee3(file, repository) {
        var content, extensionFile;
        return (_regenerator || _load_regenerator()).default.wrap(function _callee3$(_context3) {
          while (1) {
            switch (_context3.prev = _context3.next) {
              case 0:
                _context3.next = 2;
                return file.file.load(repository);

              case 2:
                content = _context3.sent;
                extensionFile = new ExtensionFile({ base: '.', path: file.name, contents: content.contents });

                extensionFile.file = (_source || _load_source()).default.from(extensionFile.contents);
                extensionFile.name = file.name;
                return _context3.abrupt('return', extensionFile);

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

      function loadFromExtensionFileModel(_x8, _x9) {
        return _ref3.apply(this, arguments);
      }

      return loadFromExtensionFileModel;
    }()

    /**
     * Util function to transform the file from Ref to string
     * Used in version.toObject
     * The opposite action of fromObjectToModelObject
     * @param {*} file
     */

  }, {
    key: 'fromModelObjectToObject',
    value: function fromModelObjectToObject(file) {
      return {
        name: file.name,
        file: file.file.toString()
      };
    }

    /**
     * Util function to transform the file from string to Ref
     * Used in version.parse
     * The opposite action of fromModelObjectToObject
     * @param {*} file
     */

  }, {
    key: 'fromObjectToModelObject',
    value: function fromObjectToModelObject(file) {
      return {
        name: file.name,
        file: new (_objects || _load_objects()).Ref(file.file)
      };
    }
  }]);

  return ExtensionFile;
}((_sources || _load_sources()).AbstractVinyl);

exports.default = ExtensionFile;