package cz.vutbr.feec.session.gnp;

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

import org.apache.log4j.Logger;

import cz.vutbr.feec.session.SessionThreadOut;

/**
 * Vysila pres unicast zpetnou vazbu nadrazenemu feedback targetu.
 * @author Radim Burget
 */
public class ThreadOut extends SessionThreadOut {

	private static Logger logger = Logger.getLogger(ThreadOut.class
			.getName());
	private GNPSessionStatus session;
	
	private DatagramSocket socket;
	
	private DatagramPacket packet;
	
	private byte[] buffer;
	
	public ThreadOut(InetAddress address, int port, int rsiTime) throws SocketException {
		setName("TTP-FT(out unicast)");
		socket = new DatagramSocket();
		buffer = new byte[1500];
		packet = new DatagramPacket(buffer, 4, address, port);
	}

	@Override
	public void run() {
		logger.debug("STARTED");
		while(!isStopped()) {
			try {
				sleep(1000);
				// Sending the RSI packet
				RSIPacket pkt = new RSIPacket();
				pkt.setSSRC(1<<31);
				pkt.setSSRCSummarized(1<<31);
				
				socket.send(packet);
				logger.debug("RSI sent");
			} catch (InterruptedException e) {
				if(isStopped()) break;
			} catch (IOException e) {
				e.printStackTrace();
				System.exit(-1);
			}
			// process packet
		}
		socket.close();
		logger.debug("FINISHED");
	}

	protected void setSession(GNPSessionStatus session) {
		this.session = session;
	}

	protected GNPSessionStatus getSession() {
		return session;
	}
	
	public void setFeedback(InetAddress address, int port) {
		packet.setAddress(address);
		packet.setPort(port);
	}
}
