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 RTPTransmitter implements Runnable, RTPAppIntf {

    private static final SmackLogger LOGGER     = SmackLogger.getLogger(SenderMediaManager.class);
    private RTPSession               rtpSession = null;
    private boolean                  killme     = false;

    public RTPTransmitter(String remoteIP, int port) {

	DatagramSocket rtpSocket = null;
	int rtpPort = 0;

	try {
	    rtpPort = getFreePort();
	    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);
	rtpSession.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));
	    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) {
	// On envoie uniquement
    }

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

    private void start() {
	LOGGER.info("Debut envoi de donnees par RTPTransmitter");
	while (!killme) {
	    rtpSession.sendData(null);
	}

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

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

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

    }

}
