package test;

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

import javax.swing.JButton;
import javax.swing.JFrame;

import jp.ac.naka.ec.entity.AbstractEntity;
import jp.ac.naka.ec.entity.EntityEvent;
import jp.ac.naka.ec.entity.EntityType;

/**
 * テスト用Entity。ボタンを押すとイベントを発火。
 * 
 * @author Takashi Kasuya
 * 
 */

public class ButtonEntity extends AbstractEntity {
	private String name = "ButtonEntity";

	String message = "Push Button!";

	@Override
	public void init() {
		new ButtonFrame(name, this);
		setEntityType(EntityType.SENSOR);
	}

	public void receiveMessage(EntityEvent e) {
		System.out.println("Button : " + e.getMessage());
	}

	@Override
	public void removedEntity(EntityEvent evt) {
		System.out.println("Remove entity :" + evt.getSource());
	}

	private void dispatchEvent() {

		// BroadCast
		this.sendMessage(message);
		

	}

	private class ButtonFrame extends JFrame {
		JButton jb = new JButton("Push!");

		final ButtonEntity parent;

		public ButtonFrame(String name, ButtonEntity p) {
			super(name);
			this.parent = p;

			jb.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					parent.dispatchEvent();
				}
			});
			getContentPane().add(jb);
			pack();
			this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
			setVisible(true);
		}
	}

	public void setButtonName(String name) {
		this.name = name;
	}

	/**
	 * ボタンを押して配信されるメッセージを設定
	 * 
	 * @param str
	 */
	public void setMessage(String str) {
		this.message = str;
	}
}
