package p.studio.controls.lifecycle;

import javafx.scene.Node;
import javafx.scene.Scene;

import java.util.Objects;

public final class StudioControlLifecycleSupport {
    private StudioControlLifecycleSupport() {
    }

    public static void install(Node node, StudioControlLifecycle lifecycle) {
        Objects.requireNonNull(node, "node");
        Objects.requireNonNull(lifecycle, "lifecycle");

        node.sceneProperty().addListener((ignored, oldScene, newScene) -> {
            if (oldScene == null && newScene != null) {
                lifecycle.subscribe();
                return;
            }

            if (oldScene != null && newScene == null) {
                lifecycle.unsubscribe();
                return;
            }

            if (oldScene != null && oldScene != newScene) {
                lifecycle.unsubscribe();
                lifecycle.subscribe();
            }
        });

        final Scene currentScene = node.getScene();
        if (currentScene != null) {
            lifecycle.subscribe();
        }
    }
}
