package eu.dnetlib.data.multimap;

import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import org.apache.commons.lang.RandomStringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.junit.Test;

public abstract class PerformanceTest {

	String URL = "http://localhost:8280/app/services/rest/multimap/values/{key}";
	private static final int N_THREADS = 1;
	private static final int N_PUTS = 5000;

	private int finished = 0;

	private class Worker implements Runnable {
		int tid;

		public Worker(int tid) {
			this.tid = tid;
		}

		public void run() {
			HttpClient client = new DefaultHttpClient();

			for (int i = 0; i < N_PUTS; i++) {
				String key = RandomStringUtils.randomAlphanumeric(20);
				String value = RandomStringUtils.randomAlphanumeric(256);
				HttpPost request = new HttpPost(URL.replace("{key}", key));
				request.setHeader("Content-Type", "application/json");
				try {
					request.setEntity(new StringEntity(value));
					HttpResponse response = client.execute(request);
					EntityUtils.consume(response.getEntity());
				} catch (ClientProtocolException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
			finished++;
			System.out.println("Finished=" + finished);
		}
	}

	@Test
	public void test() {
		ExecutorService executor = Executors.newFixedThreadPool(N_THREADS);

		for (int i = 0; i < N_THREADS; i++) {
			System.out.println("starting thread #" + i);
			Runnable worker = new Worker(i);
			executor.execute(worker);
		}

		// This will make the executor accept no new threads
		// and finish all existing threads in the queue
		executor.shutdown();
		// Wait until all threads are finish
		try {
			executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
			} catch (InterruptedException e) {
			  System.out.println("err");
			}
		System.out.println("Finished all threads");

		assert (true);
	}

}
