package de.lazyzero.NazeWiiConf.gui;

import static lu.tudor.santec.i18n.Translatrix._;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;

import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;

import de.lazyzero.NazeWiiConf.NazeWiiConf;
import de.lazyzero.NazeWiiConf.gui.widget.NazeWiiPanel;
import de.lazyzero.NazeWiiConf.gui.widget.SettingsConfWidget;
import de.lazyzero.NazeWiiConf.utils.NazeConfiguration;

public class NazeSettingsPanel extends NazeWiiPanel implements ActionListener {

	private static final long serialVersionUID = 1L;
	private JButton saveSettingsButton;
	private SettingsConfWidget settingsConfWidget;
	private NazeConfiguration nazeConfiguration;

	public NazeSettingsPanel(String title, NazeWiiConf instance) {
		super(title, instance);
		this.initGUI();
	}

	private void initGUI() {
		// create the CellContraints
		CellConstraints cc = new CellConstraints();

		// create the Layout for Panel this
		String panelColumns = "pref:grow, 3dlu, pref:grow, 3dlu, fill:pref:grow";
		String panelRows = "fill:pref:grow, 3dlu, pref";
		FormLayout panelLayout = new FormLayout(panelColumns, panelRows);
		int[][] groups = { { 1, 3, 5 } };
		panelLayout.setColumnGroups(groups);
		this.setLayout(panelLayout);

		this.settingsConfWidget = new SettingsConfWidget(
				_("settingsConfPanel.title"), instance);
		this.saveSettingsButton = new JButton(
				_("baseConfPanel.saveSettingsButton"));
		this.saveSettingsButton.addActionListener(this);

		this.add(settingsConfWidget, cc.xyw(1, 1, 5));
		this.add(saveSettingsButton, cc.xyw(1, 3, 5, "right, default"));
		

	}

	@Override
	public void actionPerformed(ActionEvent action) {
		if (action.getSource().equals(saveSettingsButton)) {
			instance.getMainPanel().getNazeCommunicator().closeCLI();
			sleep(1000);
//			instance.getMainPanel().getNazeCommunicator().openCLI();
			instance.getMainPanel().openPort(true);
		}
	}

	private void sleep(int millis) {
		try {
			Thread.sleep(millis);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void updateSettings() {
		nazeConfiguration = instance.getMainPanel().getNazeConfiguration();
		this.settingsConfWidget.updateSettings(nazeConfiguration.getSettings());
	}

	public void enableAllButtons(boolean b) {
		this.saveSettingsButton.setEnabled(b);
	}
}
