package cucumber.junit;

import cucumber.runtime.Glue;
import cucumber.runtime.Runtime;
import cucumber.runtime.model.CucumberScenario;
import gherkin.formatter.model.Step;
import org.junit.runner.Description;
import org.junit.runner.notification.RunNotifier;
import org.junit.runners.ParentRunner;
import org.junit.runners.model.InitializationError;

import java.util.HashSet;
import java.util.List;

/**
 * Runs a scenario, or a "synthetic" scenario derived from an Examples row.
 */
class ExecutionUnitRunner extends ParentRunner<Step> {
    private final Runtime runtime;
    private final CucumberScenario cucumberScenario;
    private final JUnitReporter jUnitReporter;
    private Glue glue;

    public ExecutionUnitRunner(Runtime runtime, CucumberScenario cucumberScenario, JUnitReporter jUnitReporter) throws InitializationError {
        super(ExecutionUnitRunner.class);
        this.runtime = runtime;
        this.cucumberScenario = cucumberScenario;
        this.jUnitReporter = jUnitReporter;

        this.glue = runtime.getGlue();
    }

    @Override
    protected List<Step> getChildren() {
        return cucumberScenario.getSteps();
    }

    @Override
    public String getName() {
        return cucumberScenario.getVisualName();
    }

    @Override
    protected Description describeChild(Step step) {
        return Description.createSuiteDescription(step.getKeyword() + step.getName() + "(" + getName() + ")");
    }

    @Override
    public void run(RunNotifier notifier) {
        jUnitReporter.startExecutionUnit(this, notifier);



        //No tags from the junit side?
        glue.buildBackendContextAndRunBeforeHooks(jUnitReporter, new HashSet<String>());
        cucumberScenario.runBackground(jUnitReporter.getFormatter(), jUnitReporter.getReporter(), glue);
        cucumberScenario.format(jUnitReporter);
        // Run the steps (the children)
        super.run(notifier);
        glue.runAfterHooksAndDisposeBackendContext(jUnitReporter, new HashSet<String>());

        jUnitReporter.finishExecutionUnit();
    }

    @Override
    protected void runChild(Step step, RunNotifier notifier) {
        cucumberScenario.runStep(step, jUnitReporter, glue);
    }
}

@@ -1557,18 +1557,16 @@
 fier);%0A%0A
-%0A%0A
         
@@ -1604,19 +1604,22 @@
         
-glu
+runtim
 e.buildB
@@ -1628,19 +1628,35 @@
 kend
-ContextAndR
+Worlds();%0A        runtime.r
 unBe
@@ -1704,16 +1704,17 @@
 ng%3E());%0A
+%0A
         
@@ -1803,19 +1803,22 @@
 rter(), 
-glu
+runtim
 e);%0A    
@@ -1938,19 +1938,22 @@
         
-glu
+runtim
 e.runAft
@@ -1963,32 +1963,8 @@
 ooks
-AndDisposeBackendContext
 (jUn
@@ -1966,32 +1966,33 @@
 s(jUnitReporter,
+ 
  new HashSet%3CStr
@@ -1993,32 +1993,73 @@
 et%3CString%3E());%0A%0A
+        runtime.disposeBackendWorlds();%0A%0A
         jUnitRep
@@ -2225,19 +2225,22 @@
 porter, 
-glu
+runtim
 e);%0A    

Fix junit's usage of runtime stuff