package de.lazyzero.NazeWiiConf.gui.widget;

import java.awt.Color;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.LineBorder;

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

import de.lazyzero.NazeWiiConf.NazeWiiConf;

public class SettingsWidget extends JPanel implements KeyListener {

	private static final long serialVersionUID = 1L;
	private String name;
	private int value;
	private JLabel nameLabel;
	private CellConstraints cc = new CellConstraints();
	private JTextField valueField;
	private NazeWiiConf instance;
	
	public SettingsWidget(String name, int value, NazeWiiConf instance) {
		this.name = name;
		this.value = value;
		this.instance = instance;
		
		initGUI();
	}
	
	private void initGUI() {
		cc  = new CellConstraints();
		String panelColumns = "3dlu, fill:pref:grow, 3dlu, pref, 3dlu";
		String panelRows = "pref";
		FormLayout panelLayout = new FormLayout(panelColumns, panelRows);
		this.setLayout(panelLayout);
		this.setBorder(new LineBorder(Color.LIGHT_GRAY));
		
		this.nameLabel = new JLabel(name);
		this.valueField = new JTextField(value + "", 6);
		this.valueField.addKeyListener(this);
		
		this.add(nameLabel, cc.xy(2, 1));
		this.add(valueField, cc.xy(4, 1));
	}

	public int getValue() {
		return this.value;
	}
	
	public void setValue(int value) {
		this.value = value;
		this.valueField.setText(value + "");
	}
	
	public String getName() {
		return this.name;
	}
	
	public void setName(String name) {
		this.name = name;
		this.nameLabel.setText(name);
	}

	@Override
	public void keyPressed(KeyEvent event) {
		if (event.getKeyCode() == KeyEvent.VK_ENTER) {
			try {
				this.value = Integer.parseInt(valueField.getText());
				this.instance.getMainPanel().getNazeCommunicator().writeSetting(name, value);
//				this.instance.getMainPanel().getNazeSettingsPanel().transferFocus();
			} catch (NumberFormatException e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public void keyReleased(KeyEvent event) {
	}

	@Override
	public void keyTyped(KeyEvent event) {
	}
}
