// @ts-nocheck
import * as chalk from "chalk"
import { devVite } from "./code/runVite"
import { devElectron } from "./code/runElectron"

import { ChildProcess } from "child_process"
import { watch } from "rollup"
import options from "./rollup.config"
const { startMain } = require("./webpack/runMain")

;(async () => {
  let vitePorcess = await devVite()
  console.log("[vite]", chalk.green(`vite ready.`))
  let child: ChildProcess | null
  let manualRestart = false

  startMain(async () => {
    if (child && child.kill) {
      manualRestart = true
      child.kill()
      child = null
      setTimeout(() => {
        manualRestart = false
      }, 5000)
    }
    try {
      child = await devElectron()
      console.log("[electron]", chalk.green(`electron ready.`))
      child.on("close", () => {
        if (!manualRestart) {
          // https://juejin.cn/post/6844904071682326535
          vitePorcess.kill()
          child.kill()
          process.exit()
        }
      })
    } catch (ev) {
      console.log(ev.error)
      vitePorcess.kill()
      child.kill()
      process.exit()
    }
  })
})()

// const watcher = watch(opts)
// let child: ChildProcess | null
// let manualRestart = false
// watcher.on("change", filename => {
//   const log = chalk.green(`change -- ${filename}`)
//   console.log(TAG, log)
// })
// watcher.on("event",async ev => {
//   if (ev.code === "END") {
//     if (child && child.kill) {
//       manualRestart = true
//       child.kill()
//       child = null
//       setTimeout(() => {
//         manualRestart = false
//       }, 5000)
//     }
//     try {
//       child = await runElectron()
//       console.log('[electron]', chalk.green(`electron ready.`))
//       child.on("close", () => {
//         if (!manualRestart) {
//           vitePorcess.kill()
//           child.kill()
//           process.exit()
//         }
//       })
//     } catch (ev) {
//       console.log(ev.error)
//       vitePorcess.kill()
//       child.kill()
//       process.exit()
//     }
//   } else if (ev.code === "ERROR") {
//     console.log(ev.error)
//   }
// })