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

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
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;

public class ButtonEntity extends AbstractEntity {

	JButton button;
	JTextField field;

	public ButtonEntity () {
		JFrame frame = new JFrame("ButtonEntity");
		frame.setLayout(new GridLayout(2,0));
		button = new JButton("Send Message");
		// ActionListener
		button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				String msg = field.getText();
				// フロントエンドの取得
				EntityCollaborator ec = EntityCollaborator.getInstance();
				// testというキーワードが関連付けられたEntityを探索
				Entity[] entities = ec.searchEntities("button");
				for (Entity entity:entities) {
					// 取得した参照に対してメッセージを送信
					sendMessage(msg, entity);
				}
			}
		});
		field = new JTextField();
		frame.add(field);
		frame.add(button);
		frame.pack();
		frame.setVisible(true);
		addKeyword("test");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}

	public void receiveMessage(EntityEvent evt) {
		System.out.println(evt.getMessage());
	}
	
	public static void main(String[] args) {
		
		try {
			// フロントエンドの取得
			EntityCollaborator ec = EntityCollaborator.getInstance();
			// Sipの初期化
			ec.initiateSipCore(5060);
			// DHTの初期化
			ec.initiateDHT();
			ec.addEntity(new ButtonEntity());
		} catch (Exception e) {}
	}
}
