'use strict';

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

var _fs = require('fs');

var _fs2 = _interopRequireDefault(_fs);

var _mkdirp = require('mkdirp');

var _mkdirp2 = _interopRequireDefault(_mkdirp);

var _lodash = require('lodash');

var _lodash2 = _interopRequireDefault(_lodash);

var _path = require('path');

var _path2 = _interopRequireDefault(_path);

var _bluebird = require('bluebird');

var _bluebird2 = _interopRequireDefault(_bluebird);

var _babelCore = require('babel-core');

var _debug = require('../debug');

var _debug2 = _interopRequireDefault(_debug);

var _babelConfig = require('./babel-config');

var _babelConfig2 = _interopRequireDefault(_babelConfig);

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

const babelTransformFile = _bluebird2.default.promisify(_babelCore.transformFile);
const writeFile = _bluebird2.default.promisify(_fs2.default.writeFile);

const { debug } = (0, _debug2.default)('utils-compile');

function compileFile(fileObj) {
  debug('file to transform', fileObj.srcFile);
  const dirname = _path2.default.dirname(fileObj.compiledFile);
  const newMapFile = `${fileObj.compiledFile}.map`;

  if (!_fs2.default.existsSync(dirname)) {
    _mkdirp2.default.sync(dirname);
  }

  debug('transforming file', fileObj.srcFile);
  return babelTransformFile(fileObj.srcFile, (0, _babelConfig2.default)()).then(result => _bluebird2.default.all([writeFile(fileObj.compiledFile, result.code), writeFile(newMapFile, JSON.stringify(result.map))]));
}

function compile(sockets, buildSourceMaps) {
  debug('compile');
  return new _bluebird2.default((resolve, reject) => _bluebird2.default.all(sockets.map(socket => socket.getScriptsToCompile())).then(allFiles => _lodash2.default.flatten(allFiles)).then(files => {
    debug('files to transform');
    return _bluebird2.default.all(files.map(file => compileFile(file)));
  }).then(() => {
    resolve();
  }).catch(err => {
    reject({
      errorType: 'compilationError',
      error: err
    });
  }));
}

exports.default = { compile };
module.exports = exports['default'];
//# sourceMappingURL=compile.js.map