package lpv.gui.card;

import java.awt.GridLayout;

import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;

import lpv.simulation.injector.Injector;
import lpv.simulation.injector.SinglePixelInjector;

public class SinglePixelInjectorCard extends InjectorCard {

	private JTextField xField;
	private JTextField yField;
	private JTextField dirXField;
	private JTextField dirYField;
	private JTextField dirZField;
	private JTextField strengthField;
	private JCheckBox normalizeBox;

	public SinglePixelInjectorCard() {
		JPanel contents = new JPanel();
		contents.setLayout(new GridLayout(7, 2, 5, 5));
		
		contents.add(new JLabel("Position's X-component: "));
		contents.add(xField = new JTextField("0"));
		
		contents.add(new JLabel("Position's Y-component: "));
		contents.add(yField = new JTextField("0"));
		
		contents.add(new JLabel("Strength: "));
		contents.add(strengthField = new JTextField("1.0"));
		
		contents.add(new JLabel("Direction's X-component: "));
		contents.add(dirXField = new JTextField("0.0"));
		
		contents.add(new JLabel("Direction's Y-component: "));
		contents.add(dirYField = new JTextField("0.0"));
		
		contents.add(new JLabel("Direction's Z-component: "));
		contents.add(dirZField = new JTextField("0.0"));
		
		contents.add(new JLabel());
		contents.add(normalizeBox = new JCheckBox("Normalize", true));
		
		add(contents);
	}
	
	@Override
	public Injector createInjector() {
		try {
			int x = Integer.parseInt(xField.getText());
			int y = Integer.parseInt(yField.getText());
			
			float strength = Float.parseFloat(strengthField.getText());
			float dx = Float.parseFloat(dirXField.getText());
			float dy = Float.parseFloat(dirYField.getText());
			float dz = Float.parseFloat(dirZField.getText());
			
			if(normalizeBox.isSelected() && dx+dy+dz != 0.0f) {
				float lengthInv = (float)(1.0 / Math.sqrt(dx*dx + dy*dy + dz*dz));
				dx *= lengthInv;
				dy *= lengthInv;
				dz *= lengthInv;
			}
			return new SinglePixelInjector(x, y, dx, dy, dz, strength);
		} catch(NumberFormatException e) {
			JOptionPane.showMessageDialog(this, "Invalid input. " + e.getMessage());
			return null;
		}
		
	}

}
