const path = require('path')
const fs = require('fs')
const webpack = require('webpack')

module.exports = async () => {
  process.env.SANDBOX_BUILD = true
  const {editorStyleConfig, editorSandboxConfig} = require('editor-next/scripts/editor-configs')
  const config = [editorStyleConfig, editorSandboxConfig].map((conf) => ({
    ...conf,
    output: {...conf.output, path: path.join(__dirname, 'app')},
  }))
  const editorPath = path.join(__dirname, 'app', 'editor-style.js')
  const editorLitePath = path.join(__dirname, 'app', 'editor-sandbox.js')
  try {fs.unlinkSync(editorPath)} catch (err) {}
  try {fs.unlinkSync(editorLitePath)} catch (err) {}
  const compiler = webpack(config)
  try {
    await new Promise((resolve, reject) => compiler.run((err, stats) => {
      if (err) {
        console.log(err)
        return reject(err)
      }
      if (stats.hasErrors()) {
        console.log(stats)
        return reject(stats.toJson())
      }
      resolve()
    }))
    const oldSpritePath = path.join(__dirname, 'app', 'sprite.svg')
    const newSpritePath = path.join(__dirname, 'app', 'sandbox', 'public', 'sprite.svg')
    fs.renameSync(oldSpritePath, newSpritePath)
    console.log('done: writing file')
  } catch (e) {
    console.log(e)
    throw e
  }
}

if(!module.parent) {
  module.exports().then(() => {
    process.exit(0)
  })
}



