package multinomad.tools;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import multinomad.individuals.Population;

public class Seeds {
	private double count;
	private ArrayList<ArrayList<Double>> seeds;
	
	
	public Seeds(Population pop, int findex, double accuracy) {
		seeds = new ArrayList<ArrayList<Double>>();
		try {
			
			String cmd = "python nomad.py -f "+findex+" -a "+accuracy+" -P "+pop.asPyNomadString();
			Process p = Runtime.getRuntime().exec(cmd);
			BufferedReader stdInput = new BufferedReader(new 
	                 InputStreamReader(p.getInputStream()));

            // read the output from the command
			parseSeeds(stdInput);
			
		} catch (IOException e) {e.printStackTrace();}
	
	}
	
	private void parseSeeds(BufferedReader reader) {
		try {
			
			boolean startParsingSeeds = false;
			
			String sCurrentLine = "";
			while ((sCurrentLine = reader.readLine()) != null){
				//System.out.println(sCurrentLine);
				
				if (startParsingSeeds) {
					String str = sCurrentLine.substring(sCurrentLine.indexOf("["));
					//System.out.println("String A: "+str);
					str = str.replaceAll("\\[", "");
					//System.out.println("String B: "+str);
					str = str.replaceAll("\\]", "");
					while(str.contains("  "))//Pay attention: leaving a single space
						str = str.replaceAll("  ", " ");
					//System.out.println("String C: "+str);
					str = str.trim();
					String[] values = str.split(" ");
					//System.out.println("Values: "+values.length);
					if (!values[0].equals("")) {
						ArrayList<Double> x = new ArrayList<Double>();
						//System.out.println();
						for(int i=0;i<values.length;i++) {
							x.add(new Double(Double.parseDouble(values[i])));
							//System.out.print(" "+values[i]);
						}
						//System.out.println();
						seeds.add(x);						
					}
				}
					
				if (sCurrentLine.contains("(")) {
					startParsingSeeds = true;
					int first = sCurrentLine.indexOf("(");
					int last = sCurrentLine.indexOf(")");
					String value = sCurrentLine.substring(first+1, last-1).trim();
					count = Integer.parseInt(value);
				}	
				
			    //lastLine = sCurrentLine;
			 }
			reader.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public double getCount() {
		return count;
	}
	
	public ArrayList<ArrayList<Double>> getSeeds() {
		return seeds;
	}

}
