package cz.vutbr.feec.session.feedback;

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];
	
	private FeedbackSessionStatus status;
	
	public ThreadInUnicast(FeedbackSessionStatus status, int feedbackPort) throws SocketException {
		setName("TTP-FT(in Unicast)");
		this.status = status;
		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 (!isRunning()) 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();
	}
}
