/**
 * THE ClientMetronome.java WRITEME...
 */
package com.tootsville.tootsbook.client.util.tasks;

import java.util.Vector;

import com.google.gwt.user.client.Timer;

/**
 * Global timer class to execute all jobs on one Timer
 * 
 * @author <a href="mailto:twheys@gmail.com@resinteractive.com">Tim Heys</a>
 * 
 */
public class ClientMetronome extends Timer {

	/**
	 * execute all tasks in a queue
	 * 
	 * @param tasks queue of tasks
	 */
	private static void executeTasks (final Vector <Task> tasks) {
		for (final Task task : tasks) {
			task.execute ();
		}
	}

	/**
	 * Global tasks are maintained across “page” view changes
	 */
	private final Vector <Task> globalTasks = new Vector <Task> ();

	/**
	 * Local tasks are specific to a view
	 */
	private final Vector <Task> localTasks = new Vector <Task> ();

	/**
	 * One-shot tasks that are enqueued just for asynchronous
	 * performance
	 */
	private final Vector <Task> oneTimeTasks = new Vector <Task> ();

	/**
	 * Add a task to be performed continuously
	 * 
	 * @param task task
	 */
	public void addGlobalTask (final Task task) {
		globalTasks.add (task);
	}

	/**
	 * Add a task to be performed continuously until the view changes
	 * 
	 * @param task task
	 */
	public void addLocalTask (final Task task) {
		localTasks.add (task);
	}

	/**
	 * Add a one-time task, being performed here simply to take
	 * advantage of asynchronous processing
	 * 
	 * @param task task
	 */
	public void addOneTimeTask (final Task task) {
		oneTimeTasks.add (task);
	}

	/**
	 * Clear all tasks in the local queue, due to a “page” (view) change
	 */
	public void clearLocalTasks () {
		localTasks.clear ();
	}

	/**
	 * Executes all tasks, global and local
	 * 
	 * @see com.google.gwt.user.client.Timer#run()
	 */
	@Override
	public void run () {
		ClientMetronome.executeTasks (globalTasks);
		ClientMetronome.executeTasks (localTasks);
		ClientMetronome.executeTasks (oneTimeTasks);
		oneTimeTasks.clear ();
	}
}
