package jrummikub.util;

import static org.junit.Assert.*;

import org.junit.Test;

/**
 * Test class for {@link Event2}
 */
public class Event2Test {

	int fired, fired2, fired3, fired4;

	/** */
	@Test
	public void singleListener() {
		fired = 0;
		fired2 = 0;
		Event2<Integer, Integer> testEvent = new Event2<Integer, Integer>();
		testEvent.add(new IListener2<Integer, Integer>() {

			@Override
			public void handle(Integer n, Integer m) {
				fired += n;
				fired2 += m;
			}
		});
		assertEquals(fired, 0);
		assertEquals(fired2, 0);
		testEvent.emit(10, 5);
		assertEquals(fired, 10);
		assertEquals(fired2, 5);
		testEvent.emit(20, 45);
		assertEquals(fired, 30);
		assertEquals(fired2, 50);
	}

	/** */
	@Test
	public void twoListeners() {
		fired = 0;
		fired2 = 0;
		fired3 = 0;
		fired4 = 0;
		Event2<Integer, Integer> testEvent = new Event2<Integer, Integer>();
		testEvent.add(new IListener2<Integer, Integer>() {

			@Override
			public void handle(Integer n, Integer m) {
				fired += n;
				fired2 += m;
			}
		});
		testEvent.add(new IListener2<Integer, Integer>() {

			@Override
			public void handle(Integer n, Integer m) {
				fired3 -= n;
				fired4 -= m;
			}
		});
		assertEquals(fired, 0);
		assertEquals(fired2, 0);
		assertEquals(fired3, 0);
		assertEquals(fired4, 0);
		testEvent.emit(5, 10);
		assertEquals(fired, 5);
		assertEquals(fired2, 10);
		assertEquals(fired3, -5);
		assertEquals(fired4, -10);
	}

	/** */
	@Test
	public void removeListener() {
		fired = 0;
		fired2 = 0;
		Event2<Integer, Integer> testEvent = new Event2<Integer, Integer>();
		testEvent.add(new IListener2<Integer, Integer>() {

			@Override
			public void handle(Integer n, Integer m) {
				fired += n;
				fired2 += m;
			}
		});
		IListener2<Integer, Integer> rem = new IListener2<Integer, Integer>() {

			@Override
			public void handle(Integer n, Integer m) {
				fail();
			}
		};
		assertEquals(fired, 0);
		assertEquals(fired2, 0);
		testEvent.add(rem);
		testEvent.remove(rem);
		testEvent.emit(10, 20);
		assertEquals(fired, 10);
		assertEquals(fired2, 20);
	}

	/** */
	@Test
	public void removeListenerByConnection() {
		fired = 0;
		fired2 = 0;
		Event2<Integer, Integer> testEvent = new Event2<Integer, Integer>();
		testEvent.add(new IListener2<Integer, Integer>() {

			@Override
			public void handle(Integer n, Integer m) {
				fired += n;
				fired2 += m;
			}
		});
		IListener2<Integer, Integer> rem = new IListener2<Integer, Integer>() {

			@Override
			public void handle(Integer n, Integer m) {
				fail();
			}
		};
		assertEquals(fired, 0);
		assertEquals(fired2, 0);
		Connection connection = testEvent.add(rem);
		connection.remove();
		testEvent.emit(10, 20);
		assertEquals(fired, 10);
		assertEquals(fired2, 20);
	}
}
