package com.beem.project.beem.jingle;

import java.io.IOException;
import java.net.DatagramSocket;
import java.net.ServerSocket;

import org.jivesoftware.smackx.jingle.SmackLogger;

import jlibrtp.DataFrame;
import jlibrtp.Participant;
import jlibrtp.RTPAppIntf;
import jlibrtp.RTPSession;

public class RTPReceiver implements Runnable, RTPAppIntf{

	RTPSession rtpSession = null;
	byte[] abData = null;
	private boolean killme = false;

	private static final SmackLogger LOGGER = SmackLogger.getLogger(SenderMediaManager.class);

	public RTPReceiver(int rtpPort) {
		DatagramSocket rtpSocket = null;

		try {
			rtpSocket = new DatagramSocket(rtpPort);
		} catch (Exception e) {
			System.out.println("RTPSession failed to obtain port");
			return;
		}
		rtpSession = new RTPSession(rtpSocket, null);
		rtpSession.naivePktReception(true);
		rtpSession.RTPSessionRegister(this, null, null);
	}

	@Override
	public void run() {
		start();		
	}

	private void start() {
		LOGGER.info("Debut envoi de donnees par RTPTransmitter");
		while (!killme) {
			try { Thread.sleep(1000); } catch(Exception e) { }
		}

		try {Thread.sleep(200);} catch (Exception e) {}
		this.rtpSession.endSession();

	}

	@Override
	public int frameSize(int payloadType) {
		return 1;
	}

	@Override
	public void receiveData(DataFrame frame, Participant participant) {
		//byte[] data = frame.getConcatenatedData();		
	}

	@Override
	public void userEvent(int type, Participant[] participant) {
		//rien

	}

	public void stop() {
		this.killme  = true;
	}

	protected int getFreePort() {
		ServerSocket ss;
		int freePort = 0;

		for (int i = 0; i < 10; i++) {
			freePort = (int) (10000 + Math.round(Math.random() * 10000));
			freePort = freePort % 2 == 0 ? freePort : freePort + 1;
			try {
				ss = new ServerSocket(freePort);
				freePort = ss.getLocalPort();
				ss.close();
				return freePort;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		try {
			ss = new ServerSocket(0);
			freePort = ss.getLocalPort();
			ss.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return freePort;
	}
}
