import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;

/**
 * Suppose a spaceship races away from the earth at constant velocity v for time t
 * according to a clock on the spaceship. Einstein's Special Theory of Relativity tells 
 * us how much time u will have elapsed on earth: t^2 / u^2 = 1 - (v^2 / c^2).
 *
 * This program displays the time elapsed on earth given v and t specified by the user.
 *
 * @author Albert Einstein
 */
public class TimeDilator extends Application {

    @Override
    public void start(Stage primaryStage) {
        GridPane root = new GridPane();
        Scene scene = new Scene(root, 450, 125);

        root.setAlignment(Pos.CENTER);
        root.setVgap(10);
        root.setHgap(10);

        Label vLabel = new Label("Velocity as a fraction of light speed");
        Label tLabel = new Label("Travel time in years");
        final double defaultVelocity = 0.5;
        final double defaultTime = 10;
        TextField vTextField = new TextField("" + defaultVelocity);
        TextField tTextField = new TextField("" + defaultTime);
        Button button = new Button("Elapsed Time on Earth");
        String initLabelText = getElapsedTime(defaultVelocity, defaultTime);
        Label resultLabel = new Label(initLabelText);
 
        // place nodes in the grid pane
        root.add(vLabel, 0, 0);
        root.add(vTextField, 1, 0);
        root.add(tLabel, 0, 1);
        root.add(tTextField, 1, 1);
        root.add(button, 0, 2);
        root.add(resultLabel, 1, 2);       

        class ButtonHandler implements EventHandler<ActionEvent> {

            @Override
            public void handle(ActionEvent event) {
                double v = Double.parseDouble(vTextField.getText());
                double t = Double.parseDouble(tTextField.getText());
                resultLabel.setText(getElapsedTime(v, t));
            }
        }
        button.setOnAction(new ButtonHandler());        
        
        primaryStage.setTitle("Time Dilation Calculator");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    /**
     * Calculates the time dilation for an object moving at constant velocity v
     * (given as a fraction of light speed) for time t (in years).
     */
    private static String getElapsedTime(double v, double t) {
        double u = Math.sqrt(t * t / (1 - v * v));
        return String.format("%.2f years", u);
    }

    public static void main(String[] args) {
        launch(args);
    }
}