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

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

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SNDSubModule 
extends AbstractSubModule
{
	private Logger dbg = new Logger("SND", 0);

	public boolean receiveFromDevice(String str) {
		//
		// From @SND tell start sample.au
		// From @SND tell end sample.au
		//
		// perl.match("/From @SND tell start/", str)
		// perl.match("/From @SND tell end/", str)
		//
		Pattern pSNDTell = Pattern.compile("From @SND tell (\\S+) (.*)$");
		Matcher mSNDTell = pSNDTell.matcher(str);
		if (mSNDTell.matches()) {
			String g1 = mSNDTell.group(1);
			String g2 = mSNDTell.group(2);
			if ( g1.equals("start") ) {
				receiver_.receiveOutputBusy("audio",g2);
				return true;
			} else if ( g1.equals("end") ) {
				receiver_.receiveOutputReady("audio",g2);
				return true;
			}
		}
		return false;
	}

	public boolean startOutput(OutItem item) {
		if (!(item instanceof AudioOutItem)) return false;
		String src = ((AudioOutItem)item).getArg();
		String file = "";
		if (src.startsWith("http:")) {
			String suffix = Util.getSuffix(src);
			file = Util.mktemp(suffix);
			Util.saveUrlAsBinary(src, file);
		} else {
			file = src;
		}
		sender_.send("to @SND set Play = " + file);
		return true;
	}

	public boolean stopOutput(OutItem item) {
		// TODO 
		return item instanceof AudioOutItem;
	}

}
