const fs = require('fs-extra')
const ora = require('ora')
const chalk = require('chalk')
const webpack = require('webpack')
const config = require('../build/config-reverse')

module.exports = env => {
  const spinner = ora(`Building for ${env}...`)
  spinner.start()
  fs.emptyDirSync(config.distPath)

  const webpackConfig = require('../build/webpack')(env, config)
  const compiler = webpack(webpackConfig)
  compiler.run((err, stats) => {
    spinner.stop()

    if (err) {
      console.error(err.stack || err)
      if (err.details) {
        console.error(err.details)
      }
      return
    }

    process.stdout.write(
      stats.toString({
        children: false,
        chunks: false,
        colors: true,
        modules: false,
        chunkModules: false,
        hash: false,
      }) +
      '\n\n'
    )

    if (stats.hasErrors()) {
      return console.log(chalk.white.bgRed('Build failed.\n'))
    }

    if (stats.hasWarnings()) {
      return console.log(chalk.white.bgGreenBright(
        'Build success, but with warnings.\n'))
    }
    console.log(chalk.white.bgGreen('Build success.\n'))
  })
}