'use babel';

import repl from 'repl';
import vm from 'vm';
import NodeReplReadStream from './node-repl-read-stream';
import NodeReplWriteStream from './node-repl-write-stream';

const WELCOME_MESSAGE = 'Welcome to Node.js ' + process.version;

export default class NodeReplView {

  constructor(serializedState) {
    // Create root element
    this.element = document.createElement('div');
    this.element.classList.add('node-repl');
    this.element.classList.add('native-key-bindings');
    this.element.setAttribute('tabindex', -1);

    this.outputElement = document.createElement('div');
    this.outputElement.textContent = WELCOME_MESSAGE;

    this.element.appendChild(this.outputElement);
    this.outStream = new NodeReplWriteStream(this.outputElement);
  }

  run() {
    const textEditor = atom.workspace.getActiveTextEditor();
    const readStream = new NodeReplReadStream(textEditor.getText());
    this.appendRunMessage("Executing " + readStream.getLines() + " lines...");
    this.replServer = repl.start({
      input: readStream,
      output: this.outStream,
      ignoreUndefined: true,
      prompt: "",
      terminal: false
    });

    console.log(this.replServer.context.console);
  }

  appendRunMessage(message) {
    const row = document.createElement('p');
    row.classList.add('run-header');
    row.textContent = message;
    this.outputElement.appendChild(row);
  }

  clear() {
    this.outputElement.innerHTML = WELCOME_MESSAGE;
  }

  serialize() {}

  destroy() {
    this.replServer.
    this.element.remove();
  }

  getElement() {
    return this.element;
  }

}

@@ -43,19 +43,64 @@
 ort 
-vm from 'vm
+%7B dirname %7D from 'path';%0Aimport %7B readdirSync %7D from 'fs
 ';%0Ai
@@ -950,16 +950,135 @@
 ext());%0A
+    const filePath = textEditor.getPath();%0A    const dirPath = filePath ? %60$%7Bdirname(filePath)%7D/node_modules%60 : null;%0A%0A
     this
@@ -1095,17 +1095,17 @@
 Message(
-%22
+'
 Executin
@@ -1106,17 +1106,17 @@
 ecuting 
-%22
+'
  + readS
@@ -1134,17 +1134,17 @@
 nes() + 
-%22
+'
  lines..
@@ -1144,17 +1144,17 @@
 lines...
-%22
+'
 );%0A    t
@@ -1285,10 +1285,10 @@
 pt: 
-%22%22
+''
 ,%0A  
@@ -1324,53 +1324,205 @@
     
-console.log(this.replServer.context.console);
+if (dirPath) %7B%0A      try %7B%0A        readdirSync(dirPath);%0A        this.replServer.context.module.paths.unshift(dirPath);%0A      %7D%0A      catch (err) %7B%0A        console.warn('err:', err);%0A      %7D%0A%0A    %7D
 %0A  %7D

allow for local modules when available if repl is running on a directory tree and that tree contains a node_modules push that folder to the repl context