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 org.jlibrtp.jlibrtp.core.DataFrame;
import org.jlibrtp.jlibrtp.core.Participant;
import org.jlibrtp.jlibrtp.core.RTPAppIntf;
import org.jlibrtp.jlibrtp.core.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 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() {
	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();

    }

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

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

    }
}
