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

/*
 *  Copyright (C) 2007  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
 */

import java.awt.BorderLayout;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

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

/**
 * @author 粕谷
 * 
 */
public class SliderEntity extends AbstractEntity {

	JLabel label;

	public SliderEntity() {
		setEntityType(EntityType.SENSOR);
		JFrame frame = new JFrame("Slider");
		JPanel panel = new JPanel();
		panel.setLayout(new BorderLayout());
		frame.add(panel);
		JSlider slider = new JSlider(0, 100, 50);
		slider.addChangeListener(new MyListener());
		label = new JLabel("Value : 50");
		panel.add(slider, BorderLayout.CENTER);
		panel.add(label, BorderLayout.NORTH);
		frame.pack();
		frame.setVisible(true);
	}

	@Override
	public void receiveMessage(EntityEvent arg0) {
	}

	private class MyListener implements ChangeListener {
		int prev = 50;

		public void stateChanged(ChangeEvent evt) {
			JSlider slider = (JSlider) evt.getSource();
			int value = slider.getValue();
			label.setText("Value : " + value);
			if (Math.abs(prev - value) > 10) {
				// 取得した値をマルチキャストする．
				sendMessage("value:" + value);
				prev = value;
			}
		}

	}

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