const path = require('path')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const fs = require('fs')
const webpack = require('webpack')


const root = require.resolve("../../package.json").replace("package.json", "www")
const config = {
  entry: './app/editor/index.js',
  target: 'web',
  node: {
    fs: 'empty',
    module: 'empty',
    child_process: 'empty'
  },
  output: {
    path: path.join(__dirname, '../../www'),
    filename: 'index.js',
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          'style-loader',
          'css-loader'
        ]
      },
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        loader: 'babel-loader',
        options: {
          presets: ['env', 'react'],
          plugins: ['transform-class-properties', 'transform-object-rest-spread', 'transform-decorators-legacy']
        }
      },
    ],
  },
  plugins: [
    new webpack.NormalModuleReplacementPlugin(
      new RegExp(['eslint', 'lib', 'load-rules'].join(`\\${path.sep}`)),
      path.join(root, '../lib/block/stubs/load-rules.compiled.js')
    ),
    new CopyWebpackPlugin([
      {
        from: 'node_modules/monaco-editor/min/vs',
        to: 'vs',
      },
      {
        from: 'app/image',
        to: 'image',
      },
    ]),
  ],
  devtool: 'cheap-module-source-map'
}

module.exports = async function(fileSystem) {
  const root = require.resolve("../../package.json").replace("package.json", "www")
  config.context = path.join(root, '..')
  const compiler = webpack(config)

  fileSystem.mkdirpSync ? fileSystem.mkdirpSync(root) : require('child_process').execSync(`mkdir -p ${root}`);
  fileSystem.writeFileSync(`${root}/index.html`, fs.readFileSync(path.join(root, "../app/editor/index.html")));

  compiler.outputFileSystem = fileSystem;

  await new Promise((resolve, reject) => compiler.run((err, stats) => {
    if(err) {
      return reject(err)
    }
    if(stats.hasErrors()) {
      return reject(stats.toJson())
    }
    resolve(stats)
  }))
}

