/*
 * JGrapes Event Driven Framework
 * Copyright (C) 2016  Michael N. Lipp
 * 
 * This program is free software; you can redistribute it and/or modify it 
 * under the terms of the GNU General Public License as published by 
 * the Free Software Foundation; either version 3 of the License, or 
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but 
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 
 * for more details.
 * 
 * You should have received a copy of the GNU General Public License along 
 * with this program; if not, see <http://www.gnu.org/licenses/>.
 */

package org.jgrapes.core.internal;

import org.jgrapes.core.Channel;
import org.jgrapes.core.Event;

/**
 *
 */
class SynchronousEventProcessor extends EventProcessor {

	private boolean isRunning = false;
	
	public SynchronousEventProcessor(ComponentTree tree) {
		super(tree);
	}

	/* (non-Javadoc)
	 * @see EventProcessor#add(EventBase, org.jgrapes.core.Channel[])
	 */
	@Override
	public <T extends Event<?>> T add(T event, Channel... channels) {
		((EventBase<?>)event).generatedBy(currentlyHandling.get());
		((EventBase<?>)event).processedBy(this);
		queue.add(event, channels);
		if (isRunning) {
			return event;
		}
		isRunning = true;
		GeneratorRegistry.instance().add(this);
		run();
		isRunning = false;
		return event;
	}

	/* (non-Javadoc)
	 * @see org.jgrapes.core.internal.EventProcessor#run()
	 */
	@Override
	public synchronized void run() {
		// Save current event pipeline because a SynchronousEventPipeline
		// can be called while handling an event (from another event 
		// processor).
		InternalEventPipeline currentPipeline 
			= FeedBackPipelineFilter.getAssociatedPipeline();
		try {
			super.run();
		} finally {
			FeedBackPipelineFilter.setAssociatedPipeline(currentPipeline);;
		}
	}
	
}

@@ -1624,16 +1624,49 @@
 pipeline
+ and currently handled event%0A%09%09//
  because
@@ -1692,21 +1692,16 @@
 Pipeline
-%0A%09%09//
  can be 
@@ -1713,16 +1713,22 @@
 d while 
+%0A%09%09// 
 handling
@@ -1757,22 +1757,16 @@
 r event 
-%0A%09%09// 
 processo
@@ -1869,43 +1869,138 @@
 ;%0A%09%09
-try %7B%0A%09%09%09super.run();%0A%09%09%7D finally %7B
+EventBase%3C?%3E currentEvent = currentlyHandling.get();%0A%09%09try %7B%0A%09%09%09super.run();%0A%09%09%7D finally %7B%0A%09%09%09currentlyHandling.set(currentEvent);
 %0A%09%09%09

Save and restore currently handling event.