import fs from 'fs';
import readline from 'readline';

import Importer from './Importer';

const commandsToFunctionNames = {
  fix: 'fixImports',
  word: 'import',
  goto: 'goto',
  rewrite: 'rewriteImports',
  add: 'addImports',
};

function log(message) {
  fs.appendFile('/tmp/importjsd.log', `${message}\n`, (err) => {
    if (err) {
      throw new Error(err);
    }
  });
}

export default function daemon() {
  log('STARTING daemon');

  const rlInterface = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
    terminal: false,
  });

  rlInterface.on('line', (jsonPayload: string) => {
    log(`RECEIVED payload: ${jsonPayload}`);
    // The json payload is an array containing a job id and job details.
    const payload = JSON.parse(jsonPayload);
    const importer = new Importer(
      payload.fileContent.split('\n'), payload.pathToFile);

    // TODO: don't automatically invoke function here because of security issues
    const functionName = commandsToFunctionNames[payload.command];
    importer[functionName](payload.commandArg).then((result: Object) => {
      const jsonResponse = JSON.stringify(result);
      log(`SENDING response: ${jsonResponse}`);
      process.stdout.write(`${jsonResponse}\n`);
    }).catch((error: Object) => {
      const jsonResponse = JSON.stringify({
        error: error.stack,
      });
      log(`ERROR response: ${jsonResponse}`);
      process.stdout.write(`${jsonResponse}\n`);
    });
  });
}

@@ -267,16 +267,21 @@
 endFile(
+%0A    
 '/tmp/im
@@ -295,16 +295,41 @@
 .log', %60
+$%7Bnew Date().getTime()%7D: 
 $%7Bmessag
@@ -350,16 +350,18 @@
 %3E %7B%0A    
+  
 if (err)
@@ -363,16 +363,18 @@
 (err) %7B%0A
+  
       th
@@ -397,18 +397,22 @@
 r);%0A    
-%7D%0A
+  %7D%0A  
   %7D);%0A%7D%0A

Prepend daemon log messages with timestamp