"use strict";

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

var _open = _interopRequireDefault(require("open"));

var _webpackDevServer = _interopRequireDefault(require("webpack-dev-server"));

var _easycp = _interopRequireDefault(require("easycp"));

var _fsExtra = _interopRequireDefault(require("fs-extra"));

var _ora = _interopRequireDefault(require("ora"));

var _path = _interopRequireDefault(require("path"));

var _webpack = _interopRequireDefault(require("webpack"));

var _webpack2 = require("../webpack");

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

function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }

function start(_x, _x2) {
  return _start.apply(this, arguments);
}

function _start() {
  _start = _asyncToGenerator(function* (config, {
    spinner,
    log,
    webpackConfig,
    platform
  }) {
    const paths = config.paths,
          options = config.options,
          ports = config.ports,
          action = config.action,
          port = config.port,
          platformName = config.platformName;

    if (options.storybook) {
      _fsExtra.default.mkdirsSync(paths.storybook);

      _fsExtra.default.copySync(_path.default.resolve(__dirname, '../storybook'), paths.storybook);

      const storybookPath = _path.default.resolve(paths.root, 'storybook');

      if (_fsExtra.default.existsSync(storybookPath) && _fsExtra.default.lstatSync(storybookPath).isDirectory()) {
        _fsExtra.default.copySync(storybookPath, paths.storybook);
      }

      spinner.stop();
      yield (0, _easycp.default)(`node ${require.resolve('@storybook/react/bin')} -p ${config.ports.storybook} -c ${paths.storybook}${options.debug ? ' -- --debug' : ''}${options.verbose ? ' -- --verbose' : ''}`);
      return null;
    }

    process.noDeprecation = true;
    const webpackClientConfig = (0, _webpack2.createWebpackConfig)(config, {
      platform,
      target: 'client',
      webpackConfig
    });
    log.write('webpackClientConfig', webpackClientConfig);
    const webpackServerConfig = (0, _webpack2.createWebpackConfig)(config, {
      platform,
      target: 'server',
      webpackConfig
    });
    log.write('webpackServerConfig', webpackServerConfig);

    _fsExtra.default.mkdirsSync(_path.default.resolve(paths.dist, 'public'));

    _fsExtra.default.mkdirsSync(_path.default.resolve(paths.src, 'public'));

    _fsExtra.default.copySync(_path.default.resolve(__dirname, '../public'), _path.default.resolve(paths.dist, 'public'));

    _fsExtra.default.copySync(_path.default.resolve(paths.src, 'public'), _path.default.resolve(paths.dist, 'public'));

    spinner.stop();
    spinner = (0, _ora.default)('compiling client').start();
    const serverCompiler = (0, _webpack.default)(webpackServerConfig);
    const clientCompiler = (0, _webpack.default)(webpackClientConfig);
    const server = new _webpackDevServer.default(clientCompiler, webpackClientConfig.devServer);
    let started = false;
    yield new Promise(resolve => {
      clientCompiler.plugin('done', () => {
        if (!started) {
          spinner.succeed('compiled client');
          spinner = (0, _ora.default)('compiling server').start();
          return resolve();
        }

        return (0, _ora.default)('recompiled').succeed();
      });
    });
    yield new Promise(resolve => {
      serverCompiler.watch({
        quiet: true,
        stats: 'none'
      }, (err, stats) => {
        const _handleStats = (0, _webpack2.handleStats)(stats, config),
              errors = _handleStats.errors,
              warnings = _handleStats.warnings;

        if (errors.length) {
          spinner.fail('failed to compile server');
        } else if (!started) {
          started = true;
          spinner[warnings.length ? 'warn' : 'succeed']('compiled server');
          spinner = (0, _ora.default)(`started ${action} ${platformName}`).succeed();
        }

        return resolve();
      });
    });
    yield new Promise((resolve, reject) => {
      server.listen(ports.dev, webpackClientConfig.devServer.host, err => {
        if (err) {
          spinner.stop();
          return reject(err);
        }

        return resolve();
      });
    });
    yield new Promise(r => setTimeout(r, 3000));
    return (0, _open.default)(`http://localhost:${port}`);
  });
  return _start.apply(this, arguments);
}