
import java.io.*;
import java.util.*;
import marimba.plugin.*;
import marimba.io.*;
import marimba.util.*;

public class SurveyPlugin extends Plugin {

String results = "results.txt";
Results rdata;
File rFile;

public void init() {
	super.init();
	/* plug-in's copy of the results file */
	rdata = new Results();
	rFile = getDataFile(results);
	if (rFile.exists()) {
	try {
	    FastInputStream fs = new FastInputStream(rFile);	    
		 rdata.yestotal = Integer.parseInt(fs.readLine());
		 rdata.nototal = Integer.parseInt(fs.readLine());
		 rdata.nooptotal = Integer.parseInt(fs.readLine());
	    fs.close();
	}
	catch(IOException e) {
	    e.printStackTrace();
	}
	}
}
    
public void destroy() {
  try {
		File f = getDataFile("debug.txt");
		FastOutputStream fs = new FastOutputStream(f);
		fs.println("destroy!");
		fs.close();
	}
	catch(IOException e) {
	    e.printStackTrace();
	}
	super.destroy();
}

public void processRequest(RequestContext context) throws IOException {	
		/* grab log entries */
		Vector logs = getLogEntries(context);

		/* update results */
		for (Enumeration e = logs.elements() ; e.hasMoreElements() ; ) {
	   	 LogEntry le = (LogEntry)e.nextElement();
	   	 String s = new String(le.data, 0);
			 if (s.equals("yes")) rdata.yestotal++;
			 else if (s.equals("no")) rdata.nototal++;
			 else if (s.equals("noop")) rdata.nooptotal++;
		}		

		/* ship results back to tuner */
		String s = rdata.yestotal + "\n" + rdata.nototal + "\n" +
	  		rdata.nooptotal + "\n";
		int len = s.length();
		byte[] b = new byte[len];
		s.getBytes(0,len,b,0);
		context.addFile(results,b,IF_NEEDED);

	try {
		/* write the new data back to the local file */
		if (rFile.exists() == false) {
			File dir = new File(rFile.getParent());
			if (dir.exists() == false) 
		    	dir.mkdirs();
		}
		FastOutputStream rf = new FastOutputStream(rFile);
		rf.println(rdata.yestotal);
		rf.println(rdata.nototal);
		rf.println(rdata.nooptotal);
		rf.close();
	}
	catch (IOException e) 
	{ e.printStackTrace(); 
	}

	super.processRequest(context);
}

}


