import { Timer } from './util';
import { EventEmitter } from 'events';

class Pipeline extends EventEmitter {
  constructor() {
    super();
    this.steps = [];
    this.results = {};
  }

  after(fn) {
    let name = 'execution';
    if (typeof fn === 'string') {
      name = fn;
      fn = arguments[1];
    }
    this.on(name + '-ended', fn);
  }

  afterStep(name, fn) {
    this.on('step-ended', (evName) => {
      if (name === evName) {
        fn(this.results[name].result, this.results[name].elapsed);
      }
    });
  }

  before(fn) {
    let name = 'execution';
    if (typeof fn === 'string') {
      name = fn;
      fn = arguments[1];
    }
    this.on(name + '-started', fn);
  }

  addStep(name, lambda) {
    this.steps.push([name, lambda]);
  }

  execute(jar) {
    this.emit('execution-started', jar);
    let elapsed = Timer.time(() => {
      this._runSteps(jar);
    });
    this.emit('execution-ended', elapsed);
  }

  stepResult(name) {
    return this.results[name].result;
  }

  _runSteps(jar) {
    for (let [name, lambda] of this.steps) {
      this.emit('step-started', name);
      let elapsed = this._runStep(jar, name, lambda);
      this.emit('step-ended', name, elapsed);
    }
  }

  _runStep(jar, name, lambda) {
    let result = null;
    let elapsed = Timer.time(() => {
      result = lambda(jar);
    });
    this.results[name] = {elapsed, result };
    return elapsed;
  }
}

export {
  Pipeline
};

@@ -117,16 +117,20 @@
 tructor(
+name
 ) %7B%0A    
@@ -138,16 +138,38 @@
 uper();%0A
+    this.name = name;%0A
     this
@@ -965,16 +965,148 @@
 );%0A  %7D%0A%0A
+  log() %7B%0A    let args = %5B...arguments%5D;%0A    args%5B0%5D = '%5B' + this.name + '%5D ' + args%5B0%5D;%0A    console.log.apply(console, args);%0A  %7D%0A%0A
   stepRe

add named logging method to Pipeline