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

import java.awt.GridLayout;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;

import javax.media.Manager;
import javax.media.Player;
import javax.sdp.SessionDescription;
import javax.swing.JFrame;

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.AudioPlayer;

public class AudioTransmitterEntity extends AbstractEntity {
	Entity caller;

	AudioPlayer ap = new AudioPlayer();
	String user = "transmitter";
	String path;

	// 送信先のポート
	int port = 22225;

	public AudioTransmitterEntity() {
		// EntityTypeの設定
		setEntityType(EntityType.MEDIA_TRANSMITTER);
		addKeyword("audio_transmitter");
		// 呼び出しの番号を指定
		addKeyword("205");
		// audio file名
		File file = new File("media/B5_01002.AIF");
		try {
			path = file.toURL().toString();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void receiveMessage(EntityEvent e) {
	}

	@Override
	public SessionDescription receiveOffer(EntityEvent evt) {
		// 既にかけている場合は無視する(BUSY_HERE)
		if (caller != null)
			return null;

		caller = (Entity) evt.getSource();
		final SessionDescription sdp = evt.getSessionDescription();
		SessionDescription temp = null;
		// 着信音を鳴らす
		playSound();
		try {
			// 返信用のSDPの生成
			temp = ap.getResponseSessionDescription(user, port, sdp);
			// 送信の開始
			ap.sendMediaStream(path, sdp);
		} catch (Exception e) {
			e.printStackTrace();
		}

		Thread th = new Thread() {
			public void run() {
				try {
					// 送信の開始
					ap.receiveMediaStream(port);
					// コントローラの表示
					showController();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		};
		th.start();
		return temp;
	}

	private void playSound() {
		File file = new File("media/m-phone1.wav");
		URL url;
		try {
			url = file.toURL();
			Player player = Manager.createRealizedPlayer(url);
			player.start();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	JFrame jf;

	private void showController() {
		jf = new JFrame("controller");
		jf.setLayout(new GridLayout(2, 0));
		jf.add(ap.getTransmitterController());
		jf.add(ap.getReceiverController());
		jf.pack();
		jf.setVisible(true);
	}

	@Override
	public void receiveBye(EntityEvent e) {
		// 送受信の終了
		if (ap.isPlaying())
			ap.stopReceivingMediaStream();
		ap.stopSendingMediaStream();
		System.out.println("bye");
		caller = null;
		jf.setVisible(false);
		jf = null;
	}

	public static void main(String[] args) {
		EntityCollaborator ec = EntityCollaborator.getInstance();
		try {
			ec.initiateSipCore();
			ec.initiateDHT();
			ec.addEntity(new AudioTransmitterEntity());
		} catch (Exception e) {
			// TODO 自動生成された catch ブロック
			e.printStackTrace();
		}
	}
}
