package MeterBenchmark;
import MeterBenchmark.Client;
import MeterBenchmark.Ingest;
import MeterBenchmark.GridDBClient;

import java.util.Date;
import java.util.Stack;

class MeterBenchmark {


	public static void usage() {

		System.out.println("java MeterBenchmark -db mysql|griddb -mode ingest|extract -threads 1+ -iterations 1000+ -interval 1+ -nowait");
		System.exit(1);
	}

	public static void main(String args[]) {

		boolean debug=true;
		String db="griddb";
		String mode="ingest";
		int iterations=1000;
		int hostno=0;
		int threads=1;
		boolean nowait = false;
		int interval = 1;

		for(int i=0; i < args.length; i++)  {

			switch(args[i]) {
				case "-db":
					db=args[++i];
					break;
				case "-mode":
					mode=args[++i];
					break;
				case "-threads":
					threads=Integer.parseInt(args[++i]);
					break;
				case "-iterations":
					iterations=Integer.parseInt(args[++i]);
					break;
				case "-hostno":
					hostno=Integer.parseInt(args[++i]);
					break;
				case "-nowait":
					nowait = true;
					break;
				case "-interval":
					interval = Integer.parseInt(args[++i]);
			}



		}

		System.out.println("db: "+ db +", mode: "+mode +", hostno: "+ hostno +", threads: " + threads +", iterations: "+iterations +", interval: "+interval +", nowait: "+nowait);

		Client client = null;

		Stack<Ingest> threadsStack = new Stack<Ingest>();
		int threadsFinished = 0;
		Date timeEnd = new Date();
		Date timeStart = new Date();

		if (mode.equals("ingest")) {
			for(int i=0; i < threads; i++) {
				if (db.equals("griddb"))
					client = new GridDBClient();
				if (db.equals("mysql"))
					client = new MySQLClient();

				Ingest ingest = new Ingest(client, 1000*hostno+i, iterations, interval, nowait);
				Thread thread = new Thread(ingest);
				threadsStack.push(ingest);
				thread.start();
			}
		} else if (mode.equals("extract")) {
			timeStart = new Date();
			if (db.equals("griddb"))
				client = new GridDBClient();
			if (db.equals("mysql"))
				client = new MySQLClient();

			for(int i = 0; i < threads; i++) {
				Extract extract = new Extract(client, 1000*hostno+i);
				extract.run();
			}
			timeEnd = new Date();
			long timeElapsed = timeEnd.getTime() - timeStart.getTime();
			System.out.println("["+ mode +"] Time elapsed (in milliseconds): " + timeElapsed);
		} else 
			usage();
		
		while(!threadsStack.isEmpty()) {
			if(threadsStack.peek().finished) {
				timeEnd = threadsStack.peek().endTime;
				threadsFinished++;
				if(threadsFinished == threads) {
					long timeElapsed = timeEnd.getTime() - timeStart.getTime();
					System.out.println("["+ mode +"] Time elapsed (in milliseconds): " + timeElapsed);
				}
				threadsStack.pop();
			}
		}
		return;
		

	}

}
