package eu.dnetlib.data.multimap;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.junit.Test;

public class BulkRead {
	private static final int N_THREADS = 10;
	
	private class Worker implements Runnable {
		int tid;

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

		public void run() {
			try {
				FileInputStream fstream = new FileInputStream("/home/andrea/Desktop/processed.tsv");
				DataInputStream in = new DataInputStream(fstream);
				BufferedReader br = new BufferedReader(new InputStreamReader(in));
				String line;
				String test;
				
				// Read File Line By Line
				while ((line = br.readLine()) != null) {
					String[] tokens = line.split("\t");
					test = listValues(tokens[0]);
				}
				// Close the input stream
				in.close();
				System.out.println("Finished " + tid);
			} catch (Exception e) {// Catch exception if any
				System.err.println("Error: " + e.getMessage());
			}
			
		}
	}

	@Test
	public void feed() {
		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);
	}
	
	public String listValues(String key){
		String URL = "http://node1.t.dnet:8280/multimap/services/rest/multimap/values/{key}";
		HttpClient client = new DefaultHttpClient();

		HttpGet request = new HttpGet(URL.replace("{key}", key));
		try {
			HttpResponse response = client.execute(request);
			HttpEntity entity = response.getEntity();
			InputStream inputStream = entity.getContent();
			StringWriter writer = new StringWriter();
			IOUtils.copy(inputStream, writer, null);
			return writer.toString();
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

}
