/*
 * The MIT License
 *
 * Copyright 2018 Intuit Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package com.intuit.karate.core;

import com.intuit.karate.StepActions;
import com.intuit.karate.FeatureContext;
import com.intuit.karate.ScenarioContext;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 *
 * @author pthomas3
 */
public class FeatureExecutionUnit {

    private final ExecutionContext exec;
    private final int count;
    private final Iterator<Scenario> iterator;
    private final List<ScenarioResult> results;
    private final CountDownLatch latch;

    public FeatureExecutionUnit(ExecutionContext exec) {
        this.exec = exec;
        List<Scenario> scenarios = exec.featureContext.feature.getScenarios();
        count = scenarios.size();
        iterator = scenarios.iterator();
        results = new ArrayList(count);
        latch = new CountDownLatch(count);
    }

    private ScenarioContext lastContextExecuted;

    public void submit(Runnable next) {
        FeatureContext featureContext = exec.featureContext;
        String callName = featureContext.feature.getCallName();
        if (iterator.hasNext()) {
            Scenario scenario = iterator.next();
            if (callName != null) {
                if (!scenario.getName().matches(callName)) {
                    featureContext.logger.info("skipping scenario at line: {} - {}, needed: {}", scenario.getLine(), scenario.getName(), callName);
                    latch.countDown();
                    FeatureExecutionUnit.this.submit(next);
                    return;
                }
                featureContext.logger.info("found scenario at line: {} - {}", scenario.getLine(), callName);
            }
            Tags tags = new Tags(scenario.getTagsEffective());
            if (!tags.evaluate(featureContext.tagSelector)) {
                featureContext.logger.trace("skipping scenario at line: {} with tags effective: {}", scenario.getLine(), tags.getTags());
                latch.countDown();
                FeatureExecutionUnit.this.submit(next);
                return;
            }
            String callTag = scenario.getFeature().getCallTag();
            if (callTag != null) {
                if (!tags.contains(callTag)) {
                    featureContext.logger.trace("skipping scenario at line: {} with call by tag effective: {}", scenario.getLine(), callTag);
                    latch.countDown();
                    FeatureExecutionUnit.this.submit(next);
                    return;
                }
                featureContext.logger.info("scenario called at line: {} by tag: {}", scenario.getLine(), callTag);
            }
            // this is where the script-context and vars are inited for a scenario
            // first we set the scenario metadata
            exec.callContext.setScenarioInfo(getScenarioInfo(scenario, featureContext));
            // then the tags metadata
            exec.callContext.setTags(tags);
            // karate-config.js will be processed here 
            // when the script-context constructor is called
            StepActions actions = new StepActions(featureContext, exec.callContext);
            // we also hold a reference to the LAST scenario (in the feature)
            // for cases where the caller needs a result
            lastContextExecuted = actions.context;
            exec.result.setResultVars(actions.context.getVars());
            ScenarioExecutionUnit unit = new ScenarioExecutionUnit(scenario, actions, exec);
            // this is an elegant solution to retaining the order of scenarios 
            // in the final report - even if they run in parallel !
            results.add(unit.result);
            unit.submit(() -> {
                latch.countDown();
                if (exec.callContext.perfMode) {
                    // execute one-by-one in sequence order
                    // and yield next scenario only when previous completes
                    FeatureExecutionUnit.this.submit(next);
                }
            });
            if (!exec.callContext.perfMode) {
                // loop immediately and submit all scenarios in parallel
                FeatureExecutionUnit.this.submit(next);
            }
        } else {
            if (!exec.callContext.perfMode) {
                // wait for parallel scenario submissions to complete
                try {
                    latch.await();
                } catch (InterruptedException e) {
                    featureContext.logger.error("feature failed: {}", e.getMessage());
                }
            }
            // this is where the feature gets "populated" with stats
            // but best of all, the original order is retained
            for (ScenarioResult sr : results) {
                exec.result.addResult(sr);
            }
            if (lastContextExecuted != null) {
                lastContextExecuted.invokeAfterHookIfConfigured(true);
            }
            exec.appender.close();
            next.run();
        }
    }

    private static ScenarioInfo getScenarioInfo(Scenario scenario, FeatureContext env) {
        ScenarioInfo info = new ScenarioInfo();
        info.setFeatureDir(env.feature.getPath().getParent().toString());
        info.setFeatureFileName(env.feature.getPath().getFileName().toString());
        info.setScenarioName(scenario.getName());
        info.setScenarioDescription(scenario.getDescription());
        info.setScenarioType(scenario.isOutline() ? ScenarioOutline.KEYWORD : Scenario.KEYWORD);
        return info;
    }

}

@@ -4281,260 +4281,8 @@
 t);%0A
-            // we also hold a reference to the LAST scenario (in the feature)%0A            // for cases where the caller needs a result%0A            lastContextExecuted = actions.context;%0A            exec.result.setResultVars(actions.context.getVars());%0A
     
@@ -4643,100 +4643,263 @@
     
-if (exec.callContext.perfMode) %7B%0A                    // execute one-by-one in sequence order
+// we also hold a reference to the last scenario-context that executed%0A                // for cases where the caller needs a result%0A                lastContextExecuted = actions.context;%0A                if (exec.callContext.perfMode) %7B                    
 %0A   
@@ -4917,20 +4917,16 @@
       //
- and
  yield n
@@ -4967,16 +4967,83 @@
 mpletes%0A
+                    // and we execute one-by-one in sequence order%0A
         
@@ -5953,32 +5953,161 @@
 uted != null) %7B%0A
+                // set result map that caller will see%0A                exec.result.setResultVars(lastContextExecuted.getVars());%0A
                 

build broke again ? more comments #472