package eu.dnetlib.enabling.tools.blackboard;

import javax.annotation.Resource;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(value = SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class NotificationHandlerChainTest {

	public class RecJob implements Runnable {

		private int times;
		private int num;

		public RecJob(int num, int times) {
			this.num = num;
			this.times = times;
		}

		@Override
		public void run() {
			System.out.println("starting " + num);
			if(times >= 0)
				executor.execute(new  RecJob(num + 1, times - 1));
			try {
				Thread.sleep(4000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			System.out.println("thread finished - " + num);
		}

	}

	private static final class Job implements Runnable {
		private final int value;

		public Job(final int i) {
			value = i;
		}

		@Override
		public void run() {
			System.out.println("thread started - " + value);
			try {
				Thread.sleep(4000);
			} catch (final InterruptedException e) {
				// 
			}
			System.out.println("thread finished - " + value);
		}
	}

	@Resource
	private transient ThreadPoolTaskExecutor executor;

	@Test
	public void testDelegateNotification() throws InterruptedException {
		System.out.println(executor);

		System.out.println("executing");

		for (int i = 0; i < 100; i++)
			executor.execute(new Job(i));

		System.out.println("executed - waiting");
		Thread.sleep(2000);
		
		System.out.println("active count: " + executor.getActiveCount());
		System.out.println("current pool size: " + executor.getCorePoolSize());
		System.out.println("pool size " + executor.getPoolSize());
		
		Thread.sleep(3000);
		
		System.out.println("ok");
	}

	@Test
	public void testRecursive() throws InterruptedException {
		
		for (int i = 0; i < 4; i++)
			executor.execute(new RecJob(i * 10, 4));

		
		System.out.println("executed - waiting");
		Thread.sleep(2000);
		
		System.out.println("active count: " + executor.getActiveCount());
		System.out.println("current pool size: " + executor.getCorePoolSize());
		System.out.println("pool size " + executor.getPoolSize());
		
		Thread.sleep(3000);
		
		System.out.println("ok");
	}

}
