/**
 * 
 */
package test;

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.Entity;
import jp.ac.naka.ec.entity.EntityEvent;
import jp.ac.naka.ec.entity.EntityType;
import jp.ac.naka.ec.entity.test.ButtonEntity;

/**
 * 親を指定する例。Mainを立ち上げてから実行。
 * @author Takashi Kasuya
 *
 */
public class Main2 {

	public static void main(String[] args) {
		
		// ポート5070でListen
		EntityCollaborator ec = EntityCollaborator.getInstance(5070);
		String uri = "sip:192.168.0.13:5060";
		if (args.length > 0)
			uri = args[0];
		
		Entity button = new ButtonEntity();
		ec.addEntity(button);
		Entity slider = new SliderEntity();
		ec.addEntity(slider);
		ec.setParentURI(uri);
	}
	
	static class SliderEntity extends AbstractEntity{

		JLabel label;
		
		@Override
		public void init() {
			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;
				}
			}
			
		}
		
	}
}
