package com.beem.project.beem.jingle;

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

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

public abstract class RTPTransmitter implements Runnable, RTPAppIntf {
    protected RTPSession mRtpSession = null;
    protected boolean mKillme = false;

    public RTPTransmitter(String remoteIP, int port) {
	DatagramSocket rtpSocket = null;
	int rtpPort = 0;
	
	try {
	    rtpPort = getFreePort();
	    rtpSocket = new DatagramSocket(rtpPort);
	} catch (SocketException e) {
	    e.printStackTrace();
	    return;
	}
	mRtpSession = new RTPSession(rtpSocket, null);
	mRtpSession.naivePktReception(true);
	mRtpSession.RTPSessionRegister(this, null, null);
	mRtpSession.addParticipant(new Participant(remoteIP, rtpPort, 0));
    }

    @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));
	    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) {
	// On envoie uniquement
    }

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

    /**
     * A implementer pour chaque type d'envoi specifique.
     */
    abstract void start();

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

    @Override
    public void userEvent(int type, Participant[] participant) {
	// je sais pas ce que c'est

    }

}
