import chalk from 'chalk'
import fs from 'fs-extra'
//
import { prepareRoutes } from '../static'
import { DefaultDocument } from '../static/RootComponents'
import { startDevServer, reloadRoutes } from '../static/webpack'
import getConfig from '../static/getConfig'
import { createIndexFilePlaceholder } from '../utils'
//

let first = true

export default async function start ({
  config, isCLI, debug, silent = !isCLI,
} = {}) {
  // ensure ENV variables are set
  if (typeof process.env.NODE_ENV === 'undefined') {
    process.env.NODE_ENV = 'development'
  }
  process.env.REACT_STATIC_ENV = 'development'
  process.env.BABEL_ENV = 'development'

  // Use callback style to subscribe to changes
  await getConfig(config, async config => {
    if (debug) {
      console.log('DEBUG - Resolved static.config.js:')
      console.log(config)
    }

    if (first) {
      first = false
      // Clean the dist folder
      await fs.remove(config.paths.DIST)
    }

    // Get the site props
    const siteData = await config.getSiteData({ dev: true })

    // Resolve the base HTML template
    const Component = config.Document || DefaultDocument

    // Render an index.html placeholder
    await createIndexFilePlaceholder({
      config,
      Component,
      siteData,
    })

    // Build the dynamic routes file (react-static-routes)
    if (!silent) console.log('=> Building Routes...')
    console.time(chalk.green('=> [\u2713] Routes Built'))

    if (first) {
      first = false
    }

    await prepareRoutes({ config, opts: { dev: true } }, async config => {
      console.timeEnd(chalk.green('=> [\u2713] Routes Built'))

      reloadRoutes()

      // Build the JS bundle
      await startDevServer({ config })
    })
  })

  await new Promise(() => {
    // Do nothing, the user must exit this command
  })
}
