
import java.awt.*;
import java.net.*;
import java.io.*;
import marimba.channel.*;
import marimba.gui.*;
import marimba.io.*;

public class SurveyApplication extends ApplicationPlayerFrame {

String question = "question.txt";
String results = "results.txt";

public void start() {
   super.start();
	setTitle("Survey of the Week");

	loadQuestion();
}

public void loadQuestion() {
	try {
		URL base = new URL(context.getBase(), question);
		FastInputStream fs = new FastInputStream(base.openStream());
		util.setValue("question", fs.readLine()); 
 		fs.close();
	}
	catch (MalformedURLException e) {
		e.printStackTrace();
	}
	catch (IOException e) {
		e.printStackTrace();
	}
}

public void loadData() {
	try {
		if (context.channelFileExists(results)) {
			URL base = new URL(context.getBase(), results);
			FastInputStream fs = new FastInputStream(base.openStream());
			int yt = Integer.parseInt(fs.readLine());
			int nt = Integer.parseInt(fs.readLine());
			int not = Integer.parseInt(fs.readLine());

			float votes = yt + nt + not;
			yt = (int)((yt / votes) * 100);
			nt = (int)((nt / votes) * 100);
			not = (int)((not / votes) * 100);
			util.setValue("yestot", "Yes: " + yt);
			util.setValue("yesbar", String.valueOf(yt));
			util.setValue("notot", "No: " + nt);
			util.setValue("nobar", String.valueOf(nt));
			util.setValue("nooptot", "No Opinion: " + not);
			util.setValue("noopbar", String.valueOf(not));
 
			fs.close();
		}
	}
	catch (MalformedURLException e) {
		e.printStackTrace();
	}
	catch (IOException e) {
		e.printStackTrace();
	}
}

public void notifyInstall(String dir) {
	loadQuestion();
	loadData();
}

public boolean handleEvent(Event evt) {
	if ((evt.id == Event.ACTION_EVENT) && 
	   (evt.target instanceof CommandButtonWidget)) {
			if (util.getBoolean("yes")) context.appendLog("yes");
			else if (util.getBoolean("no")) context.appendLog("no");
			else if (util.getBoolean("noop")) context.appendLog("noop");
			context.update();

			return true;
	}
	return super.handleEvent(evt);
}

}

