package cz.vutbr.feec.imageprocessing.exewrapper;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;
import java.util.Vector;


import com.rapidminer.example.Attribute;
import com.rapidminer.example.AttributeTransformation;
import com.rapidminer.example.Attributes;
import com.rapidminer.example.Example;
import com.rapidminer.example.ExampleSet;
import com.rapidminer.example.ExampleSetFactory;
import com.rapidminer.example.table.AttributeFactory;
import com.rapidminer.example.table.DataRow;
import com.rapidminer.example.table.DataRowFactory;
import com.rapidminer.example.table.ExampleTable;
import com.rapidminer.example.table.MemoryExampleTable;
import com.rapidminer.example.table.NominalMapping;
import com.rapidminer.operator.OperatorChain;
import com.rapidminer.operator.OperatorDescription;
import com.rapidminer.operator.OperatorException;
import com.rapidminer.operator.meta.AverageBuilder;
import com.rapidminer.operator.performance.PerformanceCriterion;
import com.rapidminer.operator.performance.PerformanceVector;
import com.rapidminer.operator.performance.test.PerformanceTestSuite;
import com.rapidminer.operator.ports.InputPort;
import com.rapidminer.operator.ports.OutputPort;
import com.rapidminer.operator.ports.metadata.ExampleSetMetaData;
import com.rapidminer.operator.ports.metadata.ExampleSetPrecondition;
import com.rapidminer.operator.ports.metadata.GenerateNewMDRule;
import com.rapidminer.parameter.ParameterType;
import com.rapidminer.parameter.ParameterTypeBoolean;
import com.rapidminer.parameter.ParameterTypeDirectory;
import com.rapidminer.parameter.ParameterTypeDouble;
import com.rapidminer.parameter.ParameterTypeInt;
import com.rapidminer.parameter.ParameterTypeList;
import com.rapidminer.parameter.ParameterTypeString;
import com.rapidminer.parameter.ParameterTypeText;
import com.rapidminer.parameter.conditions.BooleanParameterCondition;
import com.rapidminer.parameter.conditions.EqualStringCondition;
import com.rapidminer.parameter.conditions.NonEqualStringCondition;
import com.rapidminer.tools.Ontology;
import com.rapidminer.tools.math.Averagable;


public class ExeWrapper extends OperatorChain{
	
	String PARAMETER_VLNKA = "vlnka";
	String PARAMETER_TYPP = "typ prahovani";
	
	String PARAMETER_NPARAMS = "pocet parametru";
	String PRAH_HL = "hlavni";
	String PARAMETER_N1 = "Prah 1";
	String PARAMETER_N1_B = "Prah 1 ano?";
	String ROZKLAD_1 = "Rozklad 1";
	
	protected OutputPort outPlug = getOutputPorts().createPort("lab");
	
	
	public ExeWrapper(OperatorDescription description) {
		super(description, "Executed Process");
	
		getTransformer().addRule(
				new GenerateNewMDRule(outPlug, ExampleSet.class));
		 
	}

	
	
	@Override
	public void doWork() throws OperatorException {
		int poc_prah = getParameterAsInt(getName("pocet_prahu", 0));
		
		int vlnka = getParameterAsInt(PARAMETER_VLNKA);
		int typp = getParameterAsInt(PARAMETER_TYPP);
		
		
		int MAX_PARAMS = 5;
		int numberOfParams = 0;
		

		double fit[] = new double[MAX_PARAMS];
		
		double prahy[] = new double[poc_prah+1];
		for (int i = 1; i <= poc_prah; i++)
		{
			prahy[i]= getParameterAsDouble(getName("PRAHovani_", i));
		}
		
		
		try
		{
			Runtime rt = Runtime.getRuntime() ;
			
			
			String path = "D:\\Projects\\Diplomka\\DTWT\\Release\\";
			String s = path + "DTWT.exe " + Integer.toString(vlnka) + " " + Integer.toString(typp) + " " + Integer.toString(poc_prah) + " ";
			
			for (int i = 1; i <= poc_prah; i++)
			{
				s += Double.toString(prahy[i]) + " ";
			}
			
			  FileWriter fw = new FileWriter("D:\\out.txt", true);
    		  
    		  
    		  fw.write(s + "        ");
    		  
    		  
			
			Process p = rt.exec(s);
			//fit = p.waitFor();
			int retval = p.waitFor();
			
			try {
		         //FileReader fr = new FileReader ("D:\\Projects\\VS9\\Diplomant\\Debug\\ret.txt");
				 FileReader fr = new FileReader ("D:\\ret.txt");
		         Scanner scan = new Scanner (fr);
		         
	    		  System.out.println(s);
	    		  System.out.println("retval = " + retval);
	         
	    		  
			      for (int i = 0; i < MAX_PARAMS; i++)
			      {
			    	  if (scan.hasNextFloat()) {

			    		  fit[i] = scan.nextFloat();
			    		  numberOfParams++;
			    		  System.out.println(fit[i]);
			    		  
			    		  String sss = ((Double)fit[i]).toString();
			    		  fw.write(sss);
			    	  }
			      }
			      
	    		  System.out.println("----");
	    		  
	    		
	    		  
	    		  
			}
			catch(Exception e)
			{
			
			}
			
			 fw.write(System.getProperty( "line.separator" ));
			 fw.close();
		}
		catch(Exception e)
		{
		
		}
		
		
		
		
		
		
		
/*
		double[][] data = new double[2][2];
		
		data[0][0] = fit;
		data[1][0] = fit;

		data[0][1] = fit + 400;
		data[1][1] = fit + 400;

		
		
		double[] label = new double[2];
		
		label[0] = 3100;
		label[1] = 3100;
				
		ExampleSet s = ExampleSetFactory.createExampleSet(data, label);
		
		
//		DataRow dr = DataRowFactory.create();
		Attribute predictedLabel = AttributeFactory.createAttribute("predicted", Ontology.REAL);
		
		ExampleTable table = s.getExampleTable();
		
//		table.getAttribute(0).setName("predicted");
		table.getAttribute(0).setBlockType(Attributes.SPECIAL);
		predictedLabel.setDefault(1000);
		table.addAttribute(predictedLabel);
		
				
		
		//table.addAttribute(predictedLabel);
		
		
		ExampleSet ss = table.createExampleSet();
		ss.getAttributes().get("predicted").setBlockType(Attributes.TYPE_PREDICTION);
		ss.getAttributes().get("label").setBlockType(Attributes.TYPE_LABEL);
		*/
		
		List<Attribute> attributes = new Vector<Attribute>();
		Attribute att = AttributeFactory.createAttribute("label", Ontology.REAL);
		attributes.add(att);
		
		Attribute pre = AttributeFactory.createAttribute("predicted", Ontology.REAL);
		attributes.add(pre);
		
		MemoryExampleTable table = new MemoryExampleTable(attributes);
		
		
		
		
		
		char decimalSeperator = '.';
		DataRowFactory ROW_FACTORY = new DataRowFactory(0, decimalSeperator);
		
		// Number of attributes
		int numOfAttrib = table.getNumberOfAttributes();

		// create data vector
		Object[] values = new Object[numOfAttrib];
		

		for (int i = 0; i < numberOfParams; i++)
		{
			values[0] = fit[i];
			values[1] = 0;	/// kam se chceme dostat ... minimalizujeme, proto na nulu
			
			
			DataRow row = ROW_FACTORY.create(values, table.getAttributes());
			table.addDataRow(row);
		}
		
		ExampleSet es = table.createExampleSet();
		
		
		es.getAttributes().setLabel(att);
		es.getAttributes().setPredictedLabel(pre);
		
/*		
		Iterator<Example> r = ss.iterator();
		while (r.hasNext()) {
			Example example = r.next();
//			Attribute at = new Attribute("predicted", "3100");
			
			
			example.setValue(predictedLabel, 1000);
			
//			s.getAttributes().setPredictedLabel(predictedLabel);
//			example.setPredictedLabel(setPredictedLabel(predictedLabel));
//			example.setPredictedLabel(3100);
			
		}
		
	*/	
		outPlug.deliver(es);		
		
	}
	
	
	private String getName(String n, int i)
	{
		return n + new Integer(i).toString();
	}
	
	@Override
	public List<ParameterType> getParameterTypes() {
		
		List<ParameterType> types = super.getParameterTypes();

		// the input images
/*		ParameterType type = new ParameterTypeInt(PARAMETER_NPARAMS, "Folder with input images.", 1,5,2);
		type.setExpert(false); 
		types.add(type);
*/

		int  max = 5;

		
		
		ParameterType vlnka = new ParameterTypeInt(PARAMETER_VLNKA, "", 0,15,0);
		vlnka.setExpert(false);
		types.add(vlnka);

		ParameterType prah = new ParameterTypeInt(PARAMETER_TYPP, "", 0,1,0);
		prah.setExpert(false);
		types.add(prah);
		
		
		ParameterType p1 = new ParameterTypeInt(getName("pocet_prahu", 0), "", 1,max,1);
		p1.setExpert(false);
		types.add(p1);

		
		

		
		for (int i = 1; i <= max; i++)
		{
			ParameterType type = new ParameterTypeDouble(getName("PRAHovani_", i), "Threshold.", -50.0,50.0,1.0);


			int start = 1;
			int m = i;
			String[] myStringArray = new String[m-start];
			for (int j = start; j < m; j++)
			{

				myStringArray[j-start] = new Integer(j).toString();
//				String[] myStringArray = new String[] {"0", "1", "2"}; 
//				type.registerDependencyCondition(new BooleanParameterCondition(this,getName("PRAH_", j), true, true));
//				type.registerDependencyCondition(new EqualStringCondition(this,getName("pokus", 0), true,  new Integer(i).toString()));
//				type.registerDependencyCondition(new ListParameterCondition(this,getName("PRAH_", j), true, true));
			}
			
			type.registerDependencyCondition(new NonEqualStringCondition(this,getName("pocet_prahu", 0), true,  myStringArray));
			type.setExpert(false);
			types.add(type);
	
		/*	
			if (i != max)
			{
				ParameterType p2 = new ParameterTypeBoolean(getName("PRAH_", i), "Define mask of the input image.",false);
				p2.setExpert(true);
				types.add(p2);
			}
			*/
		}

		
		

		
		return types;
	}
}
