package p.studio.workspaces;

import javafx.scene.Node;
import javafx.scene.layout.StackPane;
import lombok.Getter;

import java.util.EnumMap;
import java.util.Map;

public final class WorkspaceHost extends StackPane {
    private final Map<WorkspaceId, Workspace> workspaces = new EnumMap<>(WorkspaceId.class);
    @Getter
    private WorkspaceId currentWorkspaceId;

    public void register(Workspace ws) {
        workspaces.put(ws.workspaceId(), ws);

        Node r = ws.rootNode();
        r.setVisible(false);
        r.setManaged(false);
        getChildren().add(r);
    }

    public void change(final WorkspaceId id) {
        if (currentWorkspaceId == id) return;

        deactivateCurrentWorkspace();

        final var nextWorkspace = workspaces.get(id);
        if (nextWorkspace == null) {
            throw new IllegalStateException("Workspace not registered: " + id);
        }

        final var n = nextWorkspace.rootNode();
        n.setVisible(true);
        n.setManaged(true);

        currentWorkspaceId = id;
        StudioWorkspaceLifecycleSupport.activate(nextWorkspace);
    }

    public void deactivateCurrentWorkspace() {
        if (currentWorkspaceId == null) {
            return;
        }

        final var oldWorkspace = workspaces.get(currentWorkspaceId);
        if (oldWorkspace != null) {
            StudioWorkspaceLifecycleSupport.deactivate(oldWorkspace);
            final var n = oldWorkspace.rootNode();
            n.setVisible(false);
            n.setManaged(false);
        }
        currentWorkspaceId = null;
    }
}
