const chalk = require('chalk')
const electron = require('electron')
const path = require('path')
const { say } = require('cfonts')
const { spawn } = require('child_process')
const webpack = require('webpack')
// const WebpackDevServer = require('webpack-dev-server')
// const webpackHotMiddleware = require('webpack-hot-middleware')
const mainConfig = require('./webpack.main.config')
// const rendererConfig = require('./webpack.renderer.config')

let electronProcess = null
let manualRestart = false
// let hotMiddleware

function logStats(proc, data) {
  let log = ""

  log += chalk.yellow.bold(`┏ ${proc} Process ${new Array(19 - proc.length + 1).join("-")}`)
  log += "\n\n"

  if (typeof data === "object") {
    data
      .toString({
        colors: true,
        chunks: false,
      })
      .split(/\r?\n/)
      .forEach((line) => {
        log += "  " + line + "\n"
      })
  } else {
    log += `  ${data}\n`
  }

  log += "\n" + chalk.yellow.bold(`┗ ${new Array(28 + 1).join("-")}`) + "\n"

  console.log(log)
}

function buildMain () {
  return new Promise((resolve, reject) => {
    mainConfig.mode = 'production'
    webpack(mainConfig, (err, stats) => {
      if (err) {
        logStats('Main', chalk.red.bold(err))
        reject(err.stack || err)
      }else if (stats.hasErrors()) {
        let err = ''
        stats.toString({
          chunks: false,
          colors: true
        })
          .split(/\r?\n/)
          .forEach(line => {
            err += `    ${line}\n`
          })
        logStats('Main', chalk.red.bold(err))
        reject(err)
      } 
      else {
        resolve(stats.toString({
          chunks: false,
          colors: true
        }))
      }
    })
  })
}
function startMain (callback) {
  return new Promise((resolve, reject) => {
    mainConfig.entry.main = [path.join(__dirname, '../../src/main/index.dev.ts')]//.concat(mainConfig.entry.main)
    mainConfig.mode = 'development'
    const compiler = webpack(mainConfig)

    compiler.hooks.watchRun.tapAsync('watch-run', (compilation, done) => {
      logStats('Main', chalk.white.bold('compiling...'))
      // hotMiddleware.publish({ action: 'compiling' })
      done()
    })

    compiler.watch({}, (err, stats) => {
      if (err) {
        logStats('Main', chalk.red.bold(err))
        return
      }

      logStats('Main', stats)

      callback && callback()

      resolve()
    })
  })
}
module.exports = {
  startMain,
  buildMain,
}


// function init () {
  // greeting()
  // startMain()
  // Promise.all([startRenderer(), startMain()])
  //   .then(() => {
  //     startElectron()
  //   })
  //   .catch(err => {
  //     console.error(err)
  //   })
// }

// init()