package p.studio.controls.shell;

import javafx.geometry.Insets;
import javafx.scene.control.ToggleButton;
import javafx.scene.control.ToggleGroup;
import javafx.scene.control.Tooltip;
import javafx.scene.layout.VBox;
import p.studio.controls.lifecycle.StudioControlLifecycle;
import p.studio.controls.lifecycle.StudioControlLifecycleSupport;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.function.Consumer;

public final class StudioWorkspaceRailControl<T> extends VBox implements StudioControlLifecycle {
    private final Map<T, ToggleButton> buttons;
    private final ToggleGroup toggleGroup = new ToggleGroup();

    public StudioWorkspaceRailControl(
            Collection<StudioWorkspaceRailItem<T>> items,
            Consumer<T> onSelect) {
        StudioControlLifecycleSupport.install(this, this);
        getStyleClass().add("studio-workspace-rail");
        setPadding(new Insets(8));
        setSpacing(8);
        setPrefWidth(64);

        this.buttons = new HashMap<>();

        for (StudioWorkspaceRailItem<T> item : items) {
            final ToggleButton button = new ToggleButton(item.icon());
            button.setToggleGroup(toggleGroup);
            button.setFocusTraversable(false);
            button.setPrefSize(44, 44);
            button.setMinSize(44, 44);
            button.setMaxSize(44, 44);
            button.getStyleClass().addAll(
                    "studio-button",
                    "studio-button-ghost",
                    "studio-button-pill",
                    "studio-button-icon",
                    "studio-button-toggle",
                    "studio-workspace-rail-button");
            button.setTooltip(new Tooltip());
            button.getTooltip().textProperty().bind(item.label());
            button.setOnAction(ignored -> Objects.requireNonNull(onSelect, "onSelect").accept(item.id()));

            buttons.put(item.id(), button);
            getChildren().add(button);
        }
    }

    public void select(T id) {
        final ToggleButton button = buttons.get(id);
        if (button != null) {
            button.setSelected(true);
        }
    }
}
