package p.studio.controls.shell;

import javafx.beans.binding.Bindings;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.geometry.Pos;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import p.studio.Container;
import p.studio.controls.lifecycle.StudioControlLifecycle;
import p.studio.controls.lifecycle.StudioControlLifecycleSupport;
import p.studio.utilities.i18n.I18n;

public final class StudioRunSurfaceControl extends HBox implements StudioControlLifecycle {
    private final BooleanProperty running = new SimpleBooleanProperty(false);

    public StudioRunSurfaceControl() {
        StudioControlLifecycleSupport.install(this, this);
        getStyleClass().add("studio-run-surface");
        setSpacing(8);
        setAlignment(Pos.CENTER_LEFT);

        final Label icon = new Label();
        icon.getStyleClass().add("studio-run-toggle-icon");
        icon.textProperty().bind(Bindings.when(running).then("\u25A0").otherwise("\u25B6"));

        final StackPane iconShell = new StackPane(icon);
        iconShell.getStyleClass().add("studio-run-toggle-icon-shell");

        final Label text = new Label();
        text.getStyleClass().add("studio-run-toggle-text");
        text.textProperty().bind(Bindings.createStringBinding(
                () -> Container.i18n().text(running.get() ? I18n.TOOLBAR_STOP : I18n.TOOLBAR_PLAY),
                running));

        final HBox content = new HBox(8, iconShell, text);
        content.setAlignment(Pos.CENTER_LEFT);

        final Button toggleButton = new Button();
        toggleButton.getStyleClass().add("studio-run-toggle-button");
        toggleButton.graphicProperty().set(content);
        toggleButton.setOnAction(ignored -> running.set(!running.get()));

        running.addListener((ignored, oldValue, newValue) -> {
            toggleButton.getStyleClass().removeAll("studio-run-toggle-play", "studio-run-toggle-stop");
            toggleButton.getStyleClass().add(newValue ? "studio-run-toggle-stop" : "studio-run-toggle-play");
        });
        toggleButton.getStyleClass().add("studio-run-toggle-play");

        getChildren().add(toggleButton);
    }

    public boolean isRunning() {
        return running.get();
    }

    public BooleanProperty runningProperty() {
        return running;
    }
}
