package jp.ac.kyutech.mns.ist.util;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.ArrayList;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;

public class SingleSelector<E> extends JDialog {
	private static final long serialVersionUID = 5168438833044266747L;
	ArrayList<E> elements;
	ArrayList<JButton> buttons;
	public E selectedObj = null;
	public SingleSelector(ArrayList<E> elelist, JFrame parent, String title){
		super(parent, title, true);
		elements = elelist;

		buttons = new ArrayList<JButton>();

		JPanel jp = new JPanel();
		jp.setLayout(new BoxLayout(jp, BoxLayout.Y_AXIS));
		for(E ele: elements){
			ObjectHoldingJButton<E> jb = new ObjectHoldingJButton<E>(ele, this);
			jp.add(jb);
		}
		getContentPane().add(new JScrollPane(jp), BorderLayout.CENTER);

		JButton cancel = new JButton("cancel");
		cancel.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				selectedObj = null;
				setVisible(false);
			}
		});
		getContentPane().add(cancel, BorderLayout.SOUTH);
		pack();
		setLocation(parent.getLocation().x+(parent.getWidth()-this.getWidth())/2, parent.getLocation().y+(parent.getHeight()-this.getHeight())/2);
		
//		requestFocus();
	}
	public void notifySelected(E obj){
		selectedObj = obj;
		//		System.out.println("notify "+selectedObj.toString());
		setVisible(false);
	}
}

class ObjectHoldingJButton<E> extends JButton {
	private static final long serialVersionUID = -2622093728012785495L;
	E object;
	SingleSelector<E> sel;
	public ObjectHoldingJButton(E o, SingleSelector<E> _sel){
		super(o.toString());
		object = o;
		sel = _sel;

		addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				sel.notifySelected(object);
			}
		});
		
		//ESCをおしたらキャンセル．全部につけるのはメモリの無駄だが．．．ウィンドウにつけると有効にならない
		addKeyListener(new KeyAdapter(){
			@Override
			public void keyPressed(KeyEvent e) {
				if (e.getKeyCode() == 27) {// ESC
					sel.selectedObj = null;
					sel.setVisible(false);
				}
			}
		});
	}
}