package org.spbu.benchmark;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.Unmarshaller;

import org.spbu.benchmark.app.*;
public class Launcher extends LoggingSupport {
	private void printUsage(){
		System.out.println("Usage: java Launcher -t <number of threads> <scenario file>");
	}
	private void run(String args[]){
		int i = 0;
		int numberOfThreads = 0;
		List<Scenario> sList = new ArrayList<Scenario>();				
		try{
		while(i<args.length){
			if(args[i].equalsIgnoreCase("-t")){
				if(i+1>=args.length) throw new Exception("Parameter error");
				else {
					numberOfThreads = Integer.parseInt(args[++i]);					
				}
			}else{
				String fileName = args[i];
				Unmarshaller um = JAXBContext.newInstance("org.spbu.benchmark.app").createUnmarshaller();
				InputStream stream = new FileInputStream(new File(fileName));
				JAXBElement<ScenarioList> JAXBList = (JAXBElement<ScenarioList>)um.unmarshal(stream);
				sList.addAll(JAXBList.getValue().getScenarios());
			}
			i++;
		}
		}catch(Exception e){
			printUsage();
			return;
		}

		if ((numberOfThreads == 0)||(sList.size()==0))
			printUsage();
		else {


			ThreadingSettings settings = new ThreadingSettings();
			settings.setLaunchInterval(200);
			settings.setTotalThreads(numberOfThreads);
			Benchmark b = new DefaultBenchmark(sList, settings);

			try {
				BenchmarkResult bresult = b.start();
				NumberFormat f = new DecimalFormat("00.00000");
				results.info("Benchmark success\n" + bresult.succeeded()
						+ " scenarios succeeded, " + bresult.failed()
						+ " scenarios failed\n" + "Response time: "
						+ f.format((float) bresult.avgResponse() / 1000)
						+ " average, "
						+ f.format((float) bresult.maxResponse() / 1000)
						+ " max, "
						+ f.format((float) bresult.minResponse() / 1000)
						+ " min\n" + "Average throughput: "
						+ f.format(bresult.throughput()) + " requests/second");
			} catch (BenchmarkException be) {
				log.error("Error:", be);
			}
		}
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		new Launcher().run(args);
	}

}
