/**
 * $Id: GRMSubModule.java,v 1.4 2008/02/14 02:00:07 nishi Exp $
 */
package galatea.io.wrapper;

import galatea.logger.Logger;
import galatea.outitem.GrammarOutItem;
import galatea.outitem.OutItem;
import galatea.submodule.AbstractSubModule;
import galatea.util.Property;
import galatea.util.Util;

import java.nio.charset.Charset;

public class GRMSubModule extends AbstractSubModule {
	private final String XML_ENCODING = "EUC-JP";
	private Logger dbg = new Logger("GRM", 0);
	private Charset charset_ = Util.getSystemDefaultCharset();
	private Charset xmlCharset_ = Charset.forName(XML_ENCODING);
	
	private boolean dummyMode_ = Property.getAsBoolean("GRM.DummyMode", false); 
	private long lastOutputWhen_;
	private boolean waitingForReady_;

	public void doTimerTask() {
		if (dummyMode_ && waitingForReady_) {
			long curr = Util.getCurrentTimeInMillis();
			if (curr - lastOutputWhen_ > 2000) {
				dbg.print("checkFromSSM IDLE (dummy)");
				receiver_.receiveOutputReady("grammar", "(dummy output done)");
				waitingForReady_ = false;
			}
		}
	}
	
	public boolean receiveFromDevice(String str) {
		if (str.startsWith("From @GRM tell 200")) {
			logger_.inputEventReceived(str.replaceAll("From @",""));
			receiver_.receiveOutputReady("grammar", "");
			return true;
		}
		if (str.startsWith("From @GRM tell 4")) {
			logger_.inputEventReceived(str.replaceAll("From @",""));
			return true;
		}
		return false;
	}

	public boolean startOutput(OutItem item) {
		if (!(item instanceof GrammarOutItem)) return false;
		GrammarOutItem g = (GrammarOutItem)item;
		String doc = "<?xml version=\"1.0\" encoding=\"" 
			+ XML_ENCODING + "\"?>" + g.getDocument();
		String location = g.getLocation();
		try {
			Util.writeToFile(location + ".xml", doc, xmlCharset_);
		} catch (Exception e) {
			dbg.print(e.toString());
			return false;
		}
		String cmd = "to @GRM set ConvertGrammar = " + location;
		dbg.print("convertGrammar: " + cmd);
		sender_.send(cmd); 
		receiver_.receiveOutputBusy("grammar", "");
		if (dummyMode_) {
			lastOutputWhen_ = Util.getCurrentTimeInMillis();
			waitingForReady_ = true;
		}
		return true;
	}

	public boolean stopOutput(OutItem item) {
		return item instanceof GrammarOutItem;
	}

}
