package lpv.gui;

import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;

import lpv.gui.card.InjectorCard;
import lpv.gui.card.InjectorType;
import lpv.simulation.injector.Injector;

public class InjectorDialog extends JDialog {
	
	private JButton okButton;
	private JButton cancelButton;
	private Injector injector;
	protected InjectorCard currentInjectorCard;

	public InjectorDialog(JFrame owner) {
		super(owner, "Add injector", true);
		injector = null;
		
		setLayout(new BorderLayout());
		
		final JPanel cardPanel = new JPanel();
		final CardLayout cardLayout = new CardLayout();
		cardPanel.setLayout(cardLayout);
		add(cardPanel, BorderLayout.CENTER);
		
		JPanel typePanel = new JPanel();
		ButtonGroup typeGroup = new ButtonGroup();
		boolean first = true;
		typePanel.setLayout(new GridLayout(1, InjectorType.values().length));
		for(final InjectorType type : InjectorType.values()) {
			JRadioButton button = new JRadioButton(type.name, first);
			typePanel.add(button);
			typeGroup.add(button);
			final InjectorCard card;
			try {
				cardPanel.add(card = type.cardClass.newInstance(), type.name());
			} catch (InstantiationException e) {
				throw new RuntimeException(e);
			} catch (IllegalAccessException e) {
				throw new RuntimeException(e);
			}
			
			button.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent e) {
					cardLayout.show(cardPanel, type.name());
					currentInjectorCard = card;
				}});
			
			if(first) {
				cardLayout.show(cardPanel, type.name());
				currentInjectorCard = card;
			}
			first = false;
		}
		
		add(typePanel, BorderLayout.NORTH);
		
		JPanel buttonPanel = new JPanel();
		buttonPanel.add(okButton = new JButton("Ok"));
		okButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				if(createInjector()) {
					setVisible(false);
				}
			}});
		
		buttonPanel.add(cancelButton = new JButton("Cancel"));
		cancelButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				setVisible(false);
			}});
		add(buttonPanel, BorderLayout.SOUTH);
		
		pack();
	}

	private boolean createInjector() {
		return currentInjectorCard != null && (injector = currentInjectorCard.createInjector()) != null;
	}
	
	public Injector getInjector() {
		return injector;
	}
	
}
