package com.beem.project.beem.jingle;

import java.net.DatagramSocket;
import java.net.SocketException;

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

import com.beem.project.beem.utils.FreePort;

/**
 * abstract RTP transmitter class.
 * @author nikita
 */
public abstract class RTPTransmitter implements Runnable, RTPAppIntf {
    /**
     * RTPSession instance.
     */
    private RTPSession mRtpSession;
    /**
     * process status manipulation.
     */
    private boolean mKillme;

    /**
     * constructor.
     * @param remoteIP receiver IP.
     * @param remotePort receiver port.
     */
    public RTPTransmitter(final String remoteIP, final int remotePort) {
	DatagramSocket rtpSocket = null;
	int rtpPort = 0;

	try {
	    rtpPort = FreePort.getFreePort();
	    rtpSocket = new DatagramSocket(rtpPort);
	} catch (SocketException e) {
	    e.printStackTrace();
	    return;
	}
	setRtpSession(new RTPSession(rtpSocket, null));
	getRtpSession().naivePktReception(true);
	getRtpSession().RTPSessionRegister(this, null, null);
	getRtpSession().addParticipant(new Participant(remoteIP, remotePort, 0));
    }

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

    @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();

    /**
     * Stop the transmission.
     */
    public void stop() {
	mKillme = true;
    }

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

    }

    /**
     * mKillme setter.
     * @param killme the mKillme to set
     */
    public void setKillme(final boolean killme) {
	this.mKillme = killme;
    }

    /**
     * mKillme getter.
     * @return the mKillme.
     */
    public boolean isKillme() {
	return mKillme;
    }

    /**
     * mRtpSession setter.
     * @param rtpSession the mRtpSession to set.
     */
    public void setRtpSession(RTPSession rtpSession) {
	this.mRtpSession = rtpSession;
    }

    /**
     * mRtpSession getter.
     * @return the mRtpSession
     */
    public RTPSession getRtpSession() {
	return mRtpSession;
    }

}
