package nl.utwente.group10.ui.components.blocks;

import com.google.common.collect.ImmutableList;
import javafx.fxml.FXML;
import javafx.scene.layout.Background;
import javafx.scene.layout.BackgroundFill;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import nl.utwente.group10.ghcj.GhciException;
import nl.utwente.group10.ghcj.GhciSession;
import nl.utwente.group10.ui.CustomUIPane;
import nl.utwente.group10.ui.components.anchors.InputAnchor;

import java.util.Optional;

public class RGBBlock extends DisplayBlock {
    private InputAnchor r;
    private InputAnchor g;
    private InputAnchor b;

    @FXML
    private Pane well;

    public RGBBlock(CustomUIPane pane) {
        super(pane, "RGBBlock");

        r = this.getAllInputs().get(0);
        g = new InputAnchor(this, pane);
        b = new InputAnchor(this, pane);

        anchorSpace.getChildren().setAll(ImmutableList.of(r, g, b));
    }

    private int evaluate(InputAnchor anchor) {
        Optional<GhciSession> ghci = getPane().getGhciSession();

        if (ghci.isPresent()) {
            try {
                String result = ghci.get().pull(anchor.asExpr());
                double dbl = Double.valueOf(result);
                double clamped = Math.max(1.0, Math.min(0.0, dbl));
                return (int) Math.round(clamped * 255);
            } catch (NumberFormatException | GhciException e) {
                return 0;
            }
        } else {
            return 0;
        }
    }

    public final void invalidateConnectionState() {
        super.invalidateConnectionState();

        int rv = evaluate(r);
        int gv = evaluate(g);
        int bv = evaluate(b);

        well.setBackground(new Background(new BackgroundFill(Color.rgb(rv, gv, bv), null, null)));
    }
}

@@ -476,24 +476,38 @@
 va.util.
-O
+NoSuchElementExce
 ption
-al
 ;%0A%0Apubli
@@ -995,17 +995,26 @@
     
-Optional%3C
+try %7B%0A            
 Ghci
@@ -1024,9 +1024,8 @@
 sion
-%3E
  ghc
@@ -1058,65 +1058,16 @@
 on()
-;%0A%0A        if (ghci.isPresent()) %7B%0A            try %7B%0A    
+.get();%0A
     
@@ -1099,14 +1099,8 @@
 hci.
-get().
 pull
@@ -1122,65 +1122,9 @@
 ));%0A
-                double dbl = Double.valueOf(result);%0A    
+%0A
     
@@ -1138,23 +1138,17 @@
  double 
-clamped
+v
  = Math.
@@ -1151,17 +1151,17 @@
 ath.max(
-1
+0
 .0, Math
@@ -1169,24 +1169,39 @@
 min(
-0
+1
 .0, 
-dbl));%0A    
+Double.valueOf(result)));%0A
     
@@ -1236,15 +1236,9 @@
 und(
-clamped
+v
  * 2
@@ -1242,20 +1242,16 @@
 * 255);%0A
-    
         
@@ -1301,67 +1301,35 @@
 ion 
-e) %7B%0A                return 0;%0A            %7D%0A        %7D else
+%7C NoSuchElementException e)
  %7B%0A 

Clean up RGBBlock.evaluate