package jp.hasc.hasctool.core.runtime.source;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketTimeoutException;
import java.nio.charset.Charset;

import jp.hasc.hasctool.core.data.SignalMessage;

/**
 * UDPで受信したパケットを、文字列系列として出力します。
 * @author iwasaki
 */
public class UDPStringReceiver extends AbstractSource {
	/** logger for this class */
	private final static org.apache.commons.logging.Log LOG = org.apache.commons.logging.LogFactory
			.getLog(UDPStringReceiver.class);
	
	private static final int DEFAULT_UDP_PORT = 6666;
	private static final int UDP_TIMEOUT = 2000;

	private int port_=DEFAULT_UDP_PORT;
	private DatagramSocket socket_;

	@Override
	protected void run() throws InterruptedException {
		LOG.info("Receiving UDP packets on port " + port_ + ".");
		Charset charset = Charset.forName("UTF-8");
		byte[] buff = new byte[1024];
		DatagramPacket packet = new DatagramPacket(buff, buff.length);
		try {
			socket_ = new DatagramSocket(port_);
			socket_.setSoTimeout(UDP_TIMEOUT);
			outputMessage(SignalMessage.BEGIN);
			while (!isShutdown()) {
				try{
					socket_.receive(packet);
					byte[] data = packet.getData();
					String s = new String(data, packet.getOffset(), packet.getLength(),
							charset);
					outputMessage(s);
				}catch(SocketTimeoutException ex) {
					//LOG.debug("timeout");
				}
			}
		} catch (IOException ex) {
			LOG.warn("IOException",ex);
		} finally {
			if (socket_!=null) socket_.close();
			socket_=null;
			outputMessage(SignalMessage.END);
			LOG.info("closed.");
		}
	}

	public int getPort() {
		return port_;
	}

	public void setPort(int udpPort) {
		port_ = udpPort;
	}
}
