package com.bestbuy.fta;

import static java.util.Arrays.asList;
import static org.jbehave.core.io.CodeLocations.codeLocationFromClass;

import java.util.List;

import org.jbehave.core.Embeddable;
import org.jbehave.core.configuration.Configuration;
import org.jbehave.core.configuration.MostUsefulConfiguration;
import org.jbehave.core.embedder.Embedder;
import org.jbehave.core.io.CodeLocations;
import org.jbehave.core.io.LoadFromClasspath;
import org.jbehave.core.io.StoryFinder;
import org.jbehave.core.junit.JUnitStories;
import org.jbehave.core.reporters.StoryReporterBuilder;
import org.jbehave.core.reporters.StoryReporterBuilder.Format;
import org.jbehave.core.steps.CandidateSteps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;

import com.bestbuy.fta.steps.StepContainer;

public abstract class GlobalStories extends JUnitStories {
	@Autowired
	private ApplicationContext applicationContext;

	private String storyFinder;

	public GlobalStories(String storyFinder) {
		super();
		this.storyFinder = storyFinder;		
	}

	@Override
	public Configuration configuration() {
		Class<? extends Embeddable> embeddableClass = this.getClass();
		
		return new MostUsefulConfiguration()
				.useStoryLoader(new LoadFromClasspath(embeddableClass))
				.useStoryReporterBuilder(
						new StoryReporterBuilder()
								.withCodeLocation(
										CodeLocations
												.codeLocationFromClass(embeddableClass))
								.withDefaultFormats()
								.withFormats(Format.CONSOLE, Format.TXT,
										Format.HTML, Format.XML));
	}

	@Override
	public List<CandidateSteps> candidateSteps() {
		return getSteps().candidates(configuration());
	}

	@Override
	protected List<String> storyPaths() {
		return new StoryFinder().findPaths(
				codeLocationFromClass(this.getClass()).getFile(),
				asList(storyFinder), null);
	}

	protected String getStoryFinder() {
		return storyFinder;
	}

	protected void setStoryFinder(String storyFinder) {
		this.storyFinder = storyFinder;
	}

	public StepContainer getSteps() {
		return applicationContext.getBean(Constants.STEP_CONTAINER_BEAN, StepContainer.class);
	}
}
