'use strict';

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

var _lodash = require('lodash');

var _lodash2 = _interopRequireDefault(_lodash);

var _webpack = require('webpack');

var _webpack2 = _interopRequireDefault(_webpack);

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

var _debug2 = _interopRequireDefault(_debug);

var _webpackConfig = require('./webpack-config');

var _webpackConfig2 = _interopRequireDefault(_webpackConfig);

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

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

function prepareCompiler({ sockets, buildPath, buildSourceMaps }) {
  const entryPoints = {};
  sockets.forEach(socket => {
    _lodash2.default.extend(entryPoints, socket.getEntryPoints());
  });

  if (!_lodash2.default.isEmpty(entryPoints)) {
    return (0, _webpack2.default)((0, _webpackConfig2.default)({ entryPoints, buildPath, buildSourceMaps }));
  }
}

function prepareCompilerBig({ sockets, buildPath, buildSourceMaps }) {
  const entryPoints = {};
  sockets.forEach(socket => {
    _lodash2.default.extend(entryPoints, socket.getEntryPoints());
  });

  if (!_lodash2.default.isEmpty(entryPoints)) {
    return (0, _webpack2.default)((0, _webpackConfig2.default)({ entryPoints, buildPath, buildSourceMaps }));
  }
}

function handleCompileOutput(err, stats, resolve, reject) {
  debug('handleCompileOutput');
  if (err) {
    debug('handleCompileOutput error');
    return reject({
      errorType: 'webpackError',
      error: err
    });
  }
  if (stats.compilation.errors.length) {
    return reject({
      errorType: 'compilationError',
      error: stats.compilation.errors[0]
    });
  }
  resolve(stats);
}

function compile(sockets, buildPath, buildSourceMaps) {
  debug('compile');
  const compiler = prepareCompiler({ sockets, buildPath, buildSourceMaps });

  return new Promise((resolve, reject) => {
    if (!compiler) {
      return resolve();
    }
    compiler.run((err, stats) => handleCompileOutput(err, stats, resolve, reject));
  });
}

function watch(sockets, socketPath, resolveCallback, rejectCallback) {
  debug('start watch');
  const compiler = prepareCompiler({ sockets, socketPath, buildSourceMaps: true });
  return compiler.watch({
    aggregateTimeout: 300,
    ignored: /node_modules/
  }, (err, stats) => {
    handleCompileOutput(err, stats, resolveCallback, rejectCallback);
  });
}

function watchBig(sockets, buildPath, resolveCallback, rejectCallback) {
  debug('start watch');
  const compiler = prepareCompilerBig({ sockets, buildPath, buildSourceMaps: true });
  if (!compiler) {
    return;
  }
  compiler.watch({
    aggregateTimeout: 300,
    ignored: /node_modules/
  }, (err, stats) => {
    handleCompileOutput(err, stats, resolveCallback, rejectCallback);
  });
  return true;
}

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