/*
 *  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 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";

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

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

	private void dispatchEvent() {
		String message = "Push Button!";
		// BroadCast
		this.sendMessage(message);
		/*
		 * EntityContainer con = getContainer(); Set<Entity> e =
		 * con.getEntities(); for (Entity entity : e) { if (!entity.isLocal()) { //
		 * Set<Entity> ee = ((EntityContainer)entity).getEntities(); //if
		 * (entity.getEntityType() == EntityType.ACTUATOR) sendMessage(message,
		 * entity); } }
		 */

	}

	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;
	}
}
