package com.beem.project.beem.jingle;

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

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

public class RTPReceiver implements Runnable, RTPAppIntf {

    RTPSession                       mRtpSession = null;
    byte[]                           mAbData     = null;
    private boolean                  mKillme     = false;


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

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

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

    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;
    }

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

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

    private void start() {
	while (!mKillme) {
	    try {
		Thread.sleep(1000);
	    } catch (Exception e) {
	    }
	}

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

    }

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

    @Override
    public void userEvent(int arg0, Participant[] arg1) {
	// TODO Auto-generated method stub
	
    }
}
