package com.beem.project.beem.jingle;

import org.jivesoftware.smackx.jingle.JingleSession;
import org.jivesoftware.smackx.jingle.media.JingleMediaSession;
import org.jivesoftware.smackx.jingle.media.PayloadType;
import org.jivesoftware.smackx.jingle.nat.TransportCandidate;
import org.sipdroid.media.RtpStreamReceiver;
import org.sipdroid.media.RtpStreamSender;
import org.sipdroid.net.SipdroidSocket;

import android.content.Context;
import android.util.Log;

/**
 * Manage microphone RTP session.
 * @author nikita
 */
public class RTPAudioSession extends JingleMediaSession {

    private RtpStreamSender mSender=null;
    private RtpStreamReceiver mReceiver=null;

    /**
     * constructor.
     * @param payloadType the payload typ used
     * @param remote the remote transport info
     * @param local the local tranport info
     * @param mediaLocator don't know
     * @param jingleSession the current jingle session
     * @param ctx 
     */
    public RTPAudioSession(final PayloadType pt, final TransportCandidate remote,
	final TransportCandidate local, final String mediaLocator, final JingleSession jingleSession, Context ctx) {
	super(pt, remote, local, mediaLocator, jingleSession);
	Log.d("AUDIO", String.format("payload type : %s ipdest %s port dest %d port src %d",pt.getName(), remote.getIp(), remote.getPort(), local.getPort()));

	SipdroidSocket rtpSocket = null;
	try {
	    rtpSocket = new SipdroidSocket(local.getPort());
	} catch (Exception e) {
	    e.printStackTrace();
	}
	mSender = new RtpStreamSender(true, 8, 8000, 160, rtpSocket, remote.getIp(), remote.getPort());
	mReceiver = new RtpStreamReceiver(rtpSocket, 8);
    }

    @Override
    public void initialize() {
    }
    
    public void setSpeakerMode(final int mode) {
	mReceiver.speaker(mode);
    }

    @Override
    public void setTrasmit(boolean active) {
    }

    @Override
    public void startReceive() {
	if (mReceiver != null) {
	    mReceiver.start();
	}
    }

    @Override
    public void startTrasmit() {
	if (mSender != null) {
	    mSender.start();
	}
    }

    @Override
    public void stopReceive() {
	if (mReceiver != null) {
	    mReceiver.halt();
	    mReceiver = null;
	}

    }

    @Override
    public void stopTrasmit() {
	if (mSender != null) {
	    mSender.halt();
	    mSender = null;
	}
    }
}
