package cz.vutbr.feec.session.gnp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

import org.apache.log4j.Logger;

public class ThreadInUnicast extends ThreadIn {
	private static Logger logger = Logger.getLogger(ThreadInUnicast.class
			.getName());
	private DatagramSocket socket;
	
	private DatagramPacket packet;

	private byte[] buffer = new byte[1500];
	
	public ThreadInUnicast(int feedbackPort) throws SocketException {
		setName("MONITOR(in Unicast)");
		packet = new DatagramPacket(buffer, buffer.length);
		socket = new DatagramSocket(feedbackPort);
	}

	@Override
	public void run() {
		logger.debug("STARTED");
		while (true) {
			try {
				socket.receive(packet);
				logger.debug("Received packet length:"+packet.getLength());
				// parse
				// TODO: zpracovani prijateho paketu
			} catch (SocketException e) {
				if (isStopped()) break;
				e.printStackTrace();
				System.exit(-1);
			} catch (IOException e) {
				e.printStackTrace();
				System.exit(-1);
			}
		}
		logger.debug("FINISHED");
	}
	
	@Override
	public void stopThread() {
		super.stopThread();
		socket.close();
	}
}
