// @ts-check
/* eslint-env node */

const child_process = require('child_process');
const fs = require('fs');

const Serve = require('ember-cli/lib/commands/serve');
const Builder = require('ember-cli/lib/models/builder');
const Watcher = require('ember-cli/lib/models/watcher');

const OUT_DIR = '.e-c-ts';

/**
 * Exclude .ts files from being watched
 */
function filterTS(name) {
  if (name.startsWith('.')) {
    // these files are filtered by default
    return false;
  }

  // typescript sources are watched by `tsc --watch` instead
  return !name.endsWith('.ts');
}

class WatcherNonTS extends Watcher {
  buildOptions() {
    let options = super.buildOptions();
    options.filter = filterTS;
    return options;
  }
}

module.exports = Serve.extend({
  name: 'serve-ts',
  aliases: [],

  run(options) {
    this.project._isRunningServeTS = true;

    const builder = new Builder({
      ui: this.ui,
      outputPath: options.outputPath,
      project: this.project,
      environment: options.environment,
    });

    const watcher = new WatcherNonTS({
      ui: this.ui,
      builder,
      analytics: this.analytics,
      options,
      serving: true,
    });

    options._builder = builder;
    options._watcher = watcher;

    // TODO: typescript might be installed globally?
    const tsc = child_process.fork('node_modules/typescript/bin/tsc', [
      '--watch',
      '--outDir', '.e-c-ts',
      '--allowJs', 'false',
      '--noEmit', 'false',
      '--sourceMap', 'false', // TODO: enable if sourcemaps=true
    ], {
      silent: true, // TODO: stdout is messy
      execArgv: []
    });

    // TODO: clean up child process

    return Serve.prototype.run.call(this, options);
  }
});

@@ -1289,16 +1289,106 @@
 obally?%0A
+    // argument sequence here is meaningful; don't apply prettier.%0A    // prettier-ignore%0A
     cons
@@ -1414,16 +1414,23 @@
 ss.fork(
+%0A      
 'node_mo
@@ -1455,16 +1455,22 @@
 in/tsc',
+%0A     
  %5B%0A     
@@ -1470,16 +1470,18 @@
 %5B%0A      
+  
 '--watch
@@ -1483,16 +1483,18 @@
 watch',%0A
+  
       '-
@@ -1507,19 +1507,19 @@
 r', 
-'.e-c-ts',%0A
+OUT_DIR,%0A  
     
@@ -1548,16 +1548,18 @@
 ,%0A      
+  
 '--noEmi
@@ -1567,24 +1567,26 @@
 ', 'false',%0A
+  
       '--sou
@@ -1642,17 +1642,27 @@
 rue%0A
+  
     %5D,
+%0A     
  %7B%0A
+  
     
@@ -1708,16 +1708,18 @@
 y%0A      
+  
 execArgv
@@ -1722,22 +1722,30 @@
 Argv: %5B%5D
-%0A
+,%0A  
     %7D
+%0A    
 );%0A%0A    
@@ -1829,16 +1829,96 @@
 tions);%0A
-
   %7D
+,%0A%0A  onInterrupt() %7B%0A    if (fs.existsSync(OUT_DIR)) fs.rmdirSync(OUT_DIR);%0A  %7D,
 %0A%7D);%0A

Implement cleanup of `.e-c-ts` dir.