package dfatool.strategy.verification.fdr2;

import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Map;

import dfatool.strategy.elements.Configuration;
import dfatool.strategy.elements.ConfigurationConstants;
import dfatool.strategy.verification.IRefinementChecker;

public class RefinementChecker implements IRefinementChecker{

	@Override
	public boolean checkFile(String fileName) throws IOException, InterruptedException{
		return !executeFDR(fileName,fileName);
	}

	@Override
	public String getCounterExample() {
		// TODO Auto-generated method stub
		return null;
	}
	
	public boolean executeFDR(String fileName,String logName) throws IOException, InterruptedException{
		boolean failed = false;
		ProcessBuilder pb = new ProcessBuilder();
		Map<String, String> env = pb.environment();
		env.put("FDRHOME", ConfigurationConstants.FDR_HOME);
		pb.command(ConfigurationConstants.FDR_HOME+"/bin/fdr2","batch",Configuration.getInstance().getProjectRoot()+ConfigurationConstants.SCRIPTS_PATH + fileName);
//		try {
			Process p = pb.start();
			InputStream output = p.getInputStream();
			InputStream outputError = p.getErrorStream();
			p.waitFor();
			BufferedReader bOutput = new BufferedReader(new InputStreamReader(output));
			BufferedReader bError = new BufferedReader(new InputStreamReader(outputError));
			String line = "\n";
			FileWriter fw = new FileWriter(Configuration.getInstance().getProjectRoot()+ConfigurationConstants.LOGS_PATH + logName);
			while ((line = bOutput.readLine()) != null) {
			  failed = hasFailed(line) || failed;
			  fw.write(line+"\n");
			}
			bOutput.close();
			fw.write("=========================================================================== \n Error stream \n");
			while ( (line = bError.readLine()) != null) {
				failed = hasFailed(line) || failed;
				fw.write(line+"\n");
			}
			fw.close();
			bError.close();
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		} catch (InterruptedException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
		return failed;
	}
	
	private boolean hasFailed(String line){
		return line.startsWith("xfalse") || line.startsWith("false") 
				|| line.startsWith("syntax error") 
				|| line.startsWith("Error during compilation")
				|| line.startsWith("The CSP compiler detected a script error");
	}
	
	public static void main(String[] args) throws IOException, InterruptedException {
		RefinementChecker rc = new RefinementChecker();
		rc.checkFile("/Users/pedroribeiro/Dropbox/Mestrado/workspace/DFATool/src/dfatool/strategy/verification/fdr2/defaultFiles/deadlock.csp");
	}

}
