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

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

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

/**
 * UDPで受信したパケットを、文字列系列として出力します。
 * （NATなどの障害のある場合に使用します。）
 * @author hiro, kawa
 */

public class HUPStringReceiver 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 String DEFAULT_SERVER_IP = "133.6.157.35";
	private static final int DEFAULT_SERVER_PORT = 9999;
	private static final int DEFAULT_UDP_PORT = 6666;
	private static final int UDP_TIMEOUT = 2000;

	private String sIp_=DEFAULT_SERVER_IP;
	private int sPort_=DEFAULT_SERVER_PORT;
	private int uPort_=DEFAULT_UDP_PORT;
	private DatagramSocket socket_;

	protected void run() throws InterruptedException {
		Charset charset = Charset.forName("UTF-8");
		byte[] buff = new byte[1024];
		DatagramPacket packet = new DatagramPacket(buff, buff.length);
		try {
			socket_ = new DatagramSocket(uPort_);
			socket_.setSoTimeout(UDP_TIMEOUT);
			DatagramPacket sdpacket = new DatagramPacket(buff, buff.length);
			sdpacket.setAddress(InetAddress.getByName(sIp_));
			sdpacket.setPort(sPort_);
			System.out.println("Sending UDP packets ");
			socket_.send(sdpacket);
			System.out.println("Receiving UDP packets on port " + socket_.getLocalPort() + ".");
			outputMessage(SignalMessage.BEGIN);		

			while (!isShutdown()) {
				try{
					socket_.receive(packet);
					byte[] data = packet.getData();
					String s = new String(data, packet.getOffset(), packet.getLength(),
							charset);
					LOG.debug("Receive:"+s);
					if(!(s.contains("#"))){
						outputMessage(s);
					}else{
						
						System.out.println("Please input this PortInfo.");
					}
				}catch(SocketTimeoutException ex) {
					//LOG.debug("timeout");
					/*
					System.out.println("Err");
					ex.printStackTrace();
					*/
				}
			}
		} catch (IOException ex) {
			LOG.warn(ex);
		} finally {
			if (socket_!=null) socket_.close();
			socket_=null;
			outputMessage(SignalMessage.END);
		}
	}

		public String getServerIP() {
			return sIp_;
		}

		public void setServerIP(String ipInf) {
			sIp_ = ipInf;
		}

		public int getServerPort() {
			return sPort_;
		}

		public void setServerPort(int serverPort) {
			sPort_ = serverPort;
		}
		
		public int getUDPPort() {
			return uPort_;
		}

		public void setUDPPort(int udpPort) {
			uPort_ = udpPort;
		}	

	}
