package cz.vutbr.feec.session.feedback;

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.packets.PacketGenerateException;
import cz.vutbr.feec.packets.ttp.FTDPacket;
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 FeedbackSessionBase session;
	
	private DatagramSocket socket;
	
	private DatagramPacket packet;
	
	private byte[] buffer;
	
	private FeedbackSessionStatus status;
	
	public ThreadOut(FeedbackSessionStatus status, InetAddress address, int port, int rsiTime) throws SocketException {
		setName("TTP-FT(out unicast)");
		this.status = status;
		socket = new DatagramSocket();
		buffer = new byte[1500];
		packet = new DatagramPacket(buffer, 4, address, port);
	}

	@Override
	public void run() {
		logger.debug("STARTED");
		while(isRunning()) {
			try {
				sleep(5000);
				// Sending the RSI packet
				FTDPacket pkt = new FTDPacket();
				try {
					int len = pkt.generate(packet.getData(), 0);
					packet.setLength(len);
					socket.send(packet);
				} catch (PacketGenerateException e) {
					e.printStackTrace();
				}
				logger.debug("RSI sent");
			} catch (InterruptedException e) {
				if(isRunning()) break;
			} catch (IOException e) {
				e.printStackTrace();
				System.exit(-1);
			}
			// process packet
		}
		socket.close();
		logger.debug("FINISHED");
	}

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

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