const path = require('path');
const webpack = require('webpack');
const webpackDevMiddleware = require('webpack-dev-middleware');
const webpackHotMiddleware = require('webpack-hot-middleware');
const DevCompileDonePlugin = require('../../internals/webpack/plugins/DevCompileDonePlugin');
const emitter = require('../event');

function getIgnoredWatchRegExp() {
  // const absOutputPath = winPath(path.join(process.cwd(), outputPath));
  return process.env.WATCH_IGNORED === 'none'
    ? undefined
    : new RegExp(process.env.WATCH_IGNORED || `(node_modules)`);
}
function createWebpackMiddleware(compiler, output, config) {
  return webpackDevMiddleware(compiler, {
    // logLevel: 'warn',
    publicPath: output.publicPath,
    // silent: true,
    stats: 'errors-only',
    writeToDisk: config && config.devServer && config.devServer.writeToDisk,
    // watchOptions: {
    //   ignored: getIgnoredWatchRegExp()
    // }
  });
}

module.exports = function addDevMiddlewares(
  app,
  webpackConfig,
  config,
  { port = 8080, hostname = '127.0.0.1' },
) {

  if (!config.mfsu) {
    webpackConfig.plugins.push(
      new DevCompileDonePlugin({
        port:
          webpackConfig.devServer && webpackConfig.devServer.port
            ? webpackConfig.devServer.port || port
            : port,
        hostname:
          webpackConfig.devServer && webpackConfig.devServer.hostname
            ? webpackConfig.devServer.hostname || '127.0.0.1'
            : hostname,
        onCompileDone({ isFirstCompile, stats }) {
          if (isFirstCompile) {
            emitter.emit('onDevCompileDone', { isFirstCompile, stats });
          }
        },
        onCompileFail(error) {
          console.log(error);
        },
      }),
    );
  }

  const compiler = webpack(webpackConfig);
  const middleware = createWebpackMiddleware(
    compiler,
    webpackConfig.output,
    config,
  );
  // console.log(middleware.compiler.watching)

  app.use(middleware);
  app.use(webpackHotMiddleware(compiler));



  


  const fs = middleware.context.outputFileSystem;



  app.get('*', (req, res) => {
    fs.readFile(path.join(compiler.outputPath, 'index.html'), (err, file) => {
      if (err) {
        res.sendStatus(404);
      } else {
        res.send(file.toString());
      }
    });
  });
};
