/**
 * @author rocksama
 * @created 2017/9/27
 * @description
 *
 * watch the target files
 * build them in memory
 * test for animationFrame count
 * async component mock data
 *
 * unnecessary to build a webpack/rollup server
 *
 */
const path = require('path')
const realFS = require('fs')
const { watch } = require('rollup')
const MemoryFS = require('memory-fs')

import { getWatchOption } from './config/development'
import runServer from './server/devServer'
// import middleware from './server/middleware'

function noop() {}  // eslint-disable-line

//  the singleton
const fs = new MemoryFS()

export default function () {

  const context = {
    //  which fileSystem in use
    fileSystem: fs,
    //  workspace
    publicPath: '/runtime',
    //  load the resources in memory
    staticPath: 'runtime',
    //  use resources that the tool stores
    preferInternalResource: true,
  }

  const option = getWatchOption(process.cwd(), context)
  const watcher = watch(option, noop)
  const server = runServer(watcher, context);

  const staticPath = path.resolve(process.cwd(), context.staticPath)
  if(context.preferInternalResource
    && realFS.statSync(staticPath).isDirectory()) {
    loadResourcesFromDisk(staticPath)
  }

  ['SIGINT', 'SIGTERM'].forEach((sig) => {
    process.on(sig, () => {
      server.close();
      process.exit(); // eslint-disable-line no-process-exit
    });
  });

  watcher.on('event', e => {
    console.info(e)
    switch (e.code) {
      case 'BUNDLE_START':
        console.info('start')
        return
      case 'BUNDLE_END':
        console.info('bundle_end')
        return
      case 'END':
        console.info('end')
        //  tell the server that we need refresh our data
        //  SSE
        return
      case 'FATAL':
        console.info(e)
    }
  })
}

//  TODO: deep load
function loadResourcesFromDisk(p) {
  fs.mkdirpSync(p)
  const files = realFS.readdirSync(p)
  for (const f of files) {
    const content = realFS.readFileSync(path.resolve(p, f), 'utf8')
    fs.writeFileSync(path.resolve(p, f), content, 'utf8')
  }
}
