package net.oni2.aeinstaller.gui.settings;

import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.util.ResourceBundle;

import javax.swing.AbstractAction;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.KeyStroke;
import javax.swing.UIManager;

import net.oni2.SettingsManager;

import org.javabuilders.BuildResult;
import org.javabuilders.swing.SwingJavaBuilder;

/**
 * @author Christian Illy
 */
public class SettingsDialog extends JDialog {
	private static final long serialVersionUID = -5719515325671846620L;

	private ResourceBundle bundle = ResourceBundle
			.getBundle("net.oni2.aeinstaller.localization."
					+ getClass().getSimpleName());
	@SuppressWarnings("unused")
	private BuildResult result = SwingJavaBuilder.build(this, bundle);

	private JComboBox cmbLaF;
	private LaFComboModel laFModel;

	private JCheckBox chkNotifyOnStart;
	private JCheckBox chkNotifyDepsAfterInstall;
	private JCheckBox chkCopyIntro;
	private JCheckBox chkCopyOutro;

	/**
	 * Open the settings
	 */
	public SettingsDialog() {
		setResizable(false);

		AbstractAction closeAction = new AbstractAction() {

			private static final long serialVersionUID = 1L;

			public void actionPerformed(ActionEvent arg0) {
				dispose();
			}
		};
		KeyStroke ksCtrlW = KeyStroke
				.getKeyStroke('W', KeyEvent.CTRL_DOWN_MASK);
		getRootPane()
				.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT)
				.put(ksCtrlW, "close");
		getRootPane().getActionMap().put("close", closeAction);

		initValues();

		setLocationRelativeTo(null);
	}

	private void initValues() {
		SettingsManager set = SettingsManager.getInstance();

		laFModel = new LaFComboModel();
		cmbLaF.setModel(laFModel);

		chkNotifyOnStart.setSelected(set.get("notifyupdates", true));
		chkNotifyDepsAfterInstall.setSelected(set.get("notifyDepsAfterInstall", false));
		chkCopyIntro.setSelected(set.get("copyintro", false));
		chkCopyOutro.setSelected(set.get("copyoutro", true));
	}

	@SuppressWarnings("unused")
	private boolean save() {
		SettingsManager set = SettingsManager.getInstance();

		set.put("notifyupdates", chkNotifyOnStart.isSelected());
		set.put("notifyDepsAfterInstall", chkNotifyDepsAfterInstall.isSelected());
		set.put("copyintro", chkCopyIntro.isSelected());
		set.put("copyoutro", chkCopyOutro.isSelected());

		String oldLaf = set.get("lookandfeel", UIManager.getLookAndFeel()
				.getClass().getName());
		String newLaf = laFModel.getSelectedClassName();

		if (!newLaf.equals(oldLaf)) {
			set.put("lookandfeel", newLaf);
			JOptionPane.showMessageDialog(this,
					bundle.getString("newLaF.text"),
					bundle.getString("newLaF.title"),
					JOptionPane.INFORMATION_MESSAGE);
		}

		return true;
	}

}
