package me.alb_i986.selenium.tinafw.tasks;

import java.util.ArrayList;
import java.util.List;

import org.junit.Assert;

import me.alb_i986.selenium.tinafw.pages.Page;

/**
 * A WebTask made up of many supposedly small (sub-)tasks,
 * which in turn may be CompositeWebTask's too.
 * <p>
 * CompositeWebTask allows you to build trees of WebTask's.
 * The idea is to have many atomic WebTask's (the leaves of the tree)
 * focused on a very small user interaction.
 * And then you start build up tasks by <i>composition</i>.
 * <p>
 * <i>With CompositeWebTask you may even get rid of page objects (!)</i>,
 * and have WebTask's talk directly to PageComponent's.
 * <p>
 * CompositeWebTask exploits the
 * <a href="http://en.wikipedia.org/wiki/Composite_pattern">
 * Composite design pattern</a>.
 */
public class CompositeWebTask extends BaseWebTask {

	private List<WebTask> subtasks = new ArrayList<>();
	
	/**
	 * Add all the given subtasks to the list of components.
	 * Discards any given null task, if any.
	 */
	public CompositeWebTask(WebTask... subtasks) {
		for (WebTask subtask : subtasks) {
			if(subtask == null)
				logger.debug("Building CompositeWebTask: discarding null task");
			else
				this.subtasks.add(subtask);
		}
	}
	
	public CompositeWebTask(List<WebTask> subtasks) {
		super();
		this.subtasks = subtasks;
	}

	/**
	 * Runs each subtask in order, and finally return the
	 * page that the last task was visiting.
	 * Each subtask will run with the same user as the composite.
	 * 
	 * @throws AssertionError if the user set in this composite is null
	 */
	@Override
	public Page run(Page initialPage) {
		Page currentPage = initialPage;
		for(WebTask task : subtasks) {
			logger.info("BEGIN subtask " + task.getClass().getSimpleName());
			// before running the subtask, set the user
			Assert.assertNotNull(getUser());
			task.setUser(getUser());
			currentPage = task.run(currentPage);
			logger.info("END subtask " + task.getClass().getSimpleName());
		}
		return currentPage;
	}

}

@@ -65,16 +65,43 @@
 ayList;%0A
+import java.util.Iterator;%0A
 import j
@@ -115,16 +115,16 @@
 l.List;%0A
-
 %0Aimport 
@@ -867,16 +867,45 @@
 eWebTask
+ implements Iterable%3CWebTask%3E
  %7B%0A%0A%09pri
@@ -1728,31 +1728,27 @@
 Task task : 
-subtask
+thi
 s) %7B%0A%09%09%09logg
@@ -2029,16 +2029,16 @@
 ));%0A%09%09%7D%0A
-
 %09%09return
@@ -2055,10 +2055,234 @@
 ge;%0A%09%7D%0A%0A
+%09/**%0A%09 * The iterator for iterating over the subtasks%0A%09 * this composite is made up of.%0A%09 * %3Cp%3E%0A%09 * Backed by %7B@link List#iterator()%7D.%0A%09 */%0A%09@Override%0A%09public Iterator%3CWebTask%3E iterator() %7B%0A%09%09return subtasks.iterator();%0A%09%7D%0A%0A
 %7D%0A

make CompositeWebTask Iterable