/*
 *  Copyright (C) 2006  Takashi Kasuya <kasuya@sfc.keio.ac.jp>
 *
 * This library is free software; you can redistribute it and/or
 *　modify it under the terms of the GNU Lesser General Public
 *　License as published by the Free Software Foundation; either
 *　version 2.1 of the License, or (at your option) any later version.
 *　This library is distributed in the hope that it will be useful,
 *　but WITHOUT ANY WARRANTY; without even the implied warranty of
 *　MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *　Lesser General Public License for more details.
 *
 *　You should have received a copy of the GNU Lesser General Public
 *　License along with this library; if not, write to the Free Software
 *　Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

package jp.ac.naka.ec.entity.test;

import javax.sdp.SessionDescription;

import jp.ac.naka.ec.EntityCollaborator;
import jp.ac.naka.ec.entity.AbstractEntity;
import jp.ac.naka.ec.entity.Entity;
import jp.ac.naka.ec.entity.EntityEvent;
import jp.ac.naka.ec.entity.EntityType;
import jp.ac.naka.ec.media.MediaTransmitter;

/**
 * リクエストを受けて、ビデオリソースのストリーミングを行うEntity。ポートは44444。
 * 
 * @author Takashi Kasuya
 * 
 */
public class VideoTransmitterEntity extends AbstractEntity {
	MediaTransmitter vt;
	int port = 44444;
	String user = "transmitter";

	Entity caller;

	public VideoTransmitterEntity() {
		setEntityType(EntityType.MEDIA_TRANSMITTER);
		// キーワードの追加
		addKeyword("camera");
		vt = new MediaTransmitter();
	}

	@Override
	public void receiveMessage(EntityEvent e) {
	}

	@Override
	public SessionDescription receiveOffer(EntityEvent evt) {
		if (caller != null)
			return null;
		// オファー元のEntityの参照を保持
		caller = (Entity) evt.getSource();
		// SDPの取得
		SessionDescription sdp = evt.getSessionDescription();
		SessionDescription temp = null;
		try {
			// 返信用のSDPの作成。ユーザ名、送信用ポートを指定
			temp = vt.getResponseSessionDescription(user, port, sdp);
			if (!vt.isPlaying())
				// SDPに従いビデオの送信
				vt.sendMedia(sdp);
		} catch (Exception e) {
			e.printStackTrace();
		}
		//　返信用SDPの送信
		return temp;
	}

	@Override
	public void receiveBye(EntityEvent e) {
		if (vt.isPlaying())
			vt.close();
		caller = null;
	}

	public static void main(String[] args) {

		try {
			EntityCollaborator ec = EntityCollaborator.getInstance();
			ec.initiateSipCore();
			ec.initiateDHT();
			ec.addEntity(new VideoTransmitterEntity());
		} catch (Exception e) {
			// TODO 自動生成された catch ブロック
			e.printStackTrace();
		}
	}
}
