package t;

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

public class Lab16b extends Application {
  private double paneWidth = 400;
  private double paneHeight = 400;

  @Override
  public void start(Stage primaryStage) {
    TextField tfDecimal = new TextField();
    TextField tfHex = new TextField();
    TextField tfBinary = new TextField();
    tfDecimal.setAlignment(Pos.BOTTOM_RIGHT);
    tfHex.setAlignment(Pos.BOTTOM_RIGHT);
    tfBinary.setAlignment(Pos.BOTTOM_RIGHT);

    GridPane pane = new GridPane();
    pane.setAlignment(Pos.CENTER);
    pane.add(new Label("Decimal"), 0, 0);
    pane.add(tfDecimal, 1, 0);
    pane.add(new Label("Hex"), 0, 1);
    pane.add(tfHex, 1, 1);
    pane.add(new Label("Binary"), 0, 2);
    pane.add(tfBinary, 1, 2);

    
    Scene scene = new Scene(pane, paneWidth, paneHeight);
    primaryStage.setTitle("Lab16b");
    primaryStage.setScene(scene); 
    primaryStage.show(); 

    tfDecimal.setOnAction(e -> {    
      
      /*This is how you convert a String to a hexadecimal*/   
      String hex = Integer.toHexString(Integer.parseInt(tfDecimal.getText()));
      System.out.println(hex);
      tfHex.setText(hex);
      
      
      String binary = Integer.toBinaryString(Integer.parseInt(tfDecimal.getText()));
      tfBinary.setText(binary);
    });

    tfHex.setOnAction(e -> {
      int decimal = Integer.parseInt(tfHex.getText(), 16);
      System.out.println(decimal);
      tfDecimal.setText(String.valueOf(decimal));
      String binary = Integer.toBinaryString(decimal);
      tfBinary.setText(binary);
    });
    
    tfBinary.setOnAction(e -> {
      int sum = 0;
      
      for(int i = 1; i < tfBinary.getText().length()+1; i++){
        char place = tfBinary.getText().charAt(tfBinary.getText().length() - i);
        
        if( place == '1')
          sum += Math.pow(2, i-1);      
      }
      
      tfDecimal.setText(String.valueOf(sum));
      String hex = Integer.toHexString(Integer.parseInt(tfDecimal.getText()));
        System.out.println(hex);
        tfHex.setText(hex);
      
      });
  }

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