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

import java.awt.Component;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.UnknownHostException;

import javax.sdp.SdpException;
import javax.sdp.SessionDescription;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;

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 PhoneEntity extends AbstractEntity {
	Entity callee;
	AudioPlayer ap;
	ButtonFrame button;
	JTextField field = new JTextField("audio_transmitter");
	// 再生メディアのパス。省略するとキャプチャデバイス
	static String path = "file:///Users/kasuya/workspace/EntityCollaborator_DHT/media/B5_01002.AIF";
	// 受信用ポート
	int port = 22224;

	public PhoneEntity() {
		setEntityType(EntityType.MEDIA_RECEIVER);
		addKeyword("audio_receiver");
		ap = new AudioPlayer();
		button = new ButtonFrame("Audio Receiver");
	}

	@Override
	public void receiveMessage(EntityEvent e) {
		System.out.println("From : " + e.getSource());
		System.out.print("\t" + e.getMessage());
		sendMessage("Hello!" , (Entity)e.getSource());
	}
	
	@Override
	public void receiveAnswer(EntityEvent evt) {
		SessionDescription sdp = evt.getSessionDescription();
		try {
			System.out.println("start");
			// ストリーミングの受信の開始
			ap.receiveMediaStream(port);
			if (path != null)
				ap.sendMediaStream(sdp);
			else {
				// パスから再生
				ap.sendMediaStream(path, sdp);
			}
			Component comp = ap.getReceiverController();
			button.add(comp);
			button.pack();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void requestMedia() {
		if (callee != null)
			return;
		EntityCollaborator con = EntityCollaborator.getInstance();
		Entity[] set = null;
		SessionDescription sdp = null;
		// テキストフィールドの文字列で検索
		set = con.searchEntities(field.getText());
		try {
			// SDPの生成
			sdp = ap.getRequestSessionDescription(this);
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (SdpException e) {
			e.printStackTrace();
		}
		for (Entity entity : set) {
			// Transmitter, SIPクライアントを探してユニキャスト
			if (entity.getEntityType() == EntityType.MEDIA_TRANSMITTER
					|| entity.getEntityType() == EntityType.SOUND) {
				sendOffer(sdp, entity);
				
				callee = entity;
				break;
			}
		}
	}

	@Override
	public void receiveBye(EntityEvent e) {
		System.out.println("Receive Bye");
		if (ap.isPlaying()) {
			ap.stopReceivingMediaStream();
			ap.stopSendingMediaStream();
		}
		callee = null;
	}

	private class ButtonFrame extends JFrame {
		JButton jb = new JButton("Request Media!");
		JButton bye = new JButton("BYE");

		JPanel panel = new JPanel();

		public ButtonFrame(String name) {
			super(name);
			panel.add(jb);
			panel.add(bye);
			setLayout(new GridLayout(0, 1));
			jb.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					requestMedia();
				}

			});

			bye.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					if (callee != null) {
						sendBye(callee);
						ap.stopReceivingMediaStream();
						ap.stopSendingMediaStream();
						callee = null;
						System.out.println("end");
					}
				}
			});
			add(field);
			add(panel);

			pack();
			this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
			setVisible(true);
		}
	}

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

}
