package be.iminds.ilabt.jfed.experimenter_gui.util.ui;

import javafx.application.Platform;
import javafx.stage.Window;

/**
 * User: twalcari
 * Date: 3/19/2014
 * Time: 10:15 AM
 */
public class FXUtils {

    public static boolean centerToOwner(Window parent, final Window child) {
        if (parent == null)
            return false;

        assert child != null;
        
        

        // get center of window
        final double windowCenterX = parent.getX() + (parent.getWidth() / 2);
        final double windowCenterY = parent.getY() + (parent.getHeight() / 2);

        // verify
        if (!Double.isNaN(windowCenterX)) {
            // set a temp position
            child.setX(windowCenterX);
            child.setY(windowCenterY);

            // Since the dialog doesn't have a width or height till it's shown, calculate its position after it's shown
            Platform.runLater(() -> {
                double x = windowCenterX - (child.getWidth() / 2);
                double y = windowCenterY - (child.getHeight() / 2);

                // we don't want the top left of the dialog to shoot off the screen
                if (x < 0)
                    x = 0;
                if (y < 0)
                    y = 0;

                child.setX(x);
                child.setY(y);
            });

            return true;
        } else {
            return false;
        }
    }

}
