package p.studio.workspaces;

import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.Node;
import javafx.scene.Scene;
import p.studio.controls.lifecycle.StudioControlLifecycle;

import java.util.List;
import java.util.Objects;

public final class StudioWorkspaceLifecycleSupport {
    private StudioWorkspaceLifecycleSupport() {
    }

    public static void activate(Workspace workspace) {
        final Workspace target = Objects.requireNonNull(workspace, "workspace");
        final Node rootNode = target.rootNode();
        final Scene scene = rootNode.getScene();
        if (scene != null) {
            activateNow(target);
            return;
        }

        rootNode.sceneProperty().addListener(new ChangeListener<>() {
            @Override
            public void changed(
                    ObservableValue<? extends Scene> observable,
                    Scene oldScene,
                    Scene newScene) {
                if (newScene == null) {
                    return;
                }
                rootNode.sceneProperty().removeListener(this);
                activateNow(target);
            }
        });
    }

    public static void deactivate(Workspace workspace) {
        final Workspace target = Objects.requireNonNull(workspace, "workspace");
        target.unLoad();
        final List<StudioControlLifecycle> participants = target.lifecycleParticipants();
        for (int index = participants.size() - 1; index >= 0; index--) {
            participants.get(index).unsubscribe();
        }
    }

    private static void activateNow(Workspace workspace) {
        Platform.runLater(() -> {
            final List<StudioControlLifecycle> participants = workspace.lifecycleParticipants();
            for (StudioControlLifecycle participant : participants) {
                participant.subscribe();
            }
            workspace.load();
        });
    }
}
