package p.studio.controls.forms;

import javafx.scene.control.Button;
import javafx.scene.layout.HBox;
import p.studio.Container;
import p.studio.utilities.i18n.I18n;

public final class StudioFormActionBar extends HBox {
    private final Button changeButton = createButton(I18n.FORM_ACTION_CHANGE);
    private final Button applyButton = createButton(I18n.FORM_ACTION_APPLY);
    private final Button resetButton = createButton(I18n.FORM_ACTION_RESET);
    private final Button cancelButton = createButton(I18n.FORM_ACTION_CANCEL);

    public StudioFormActionBar(
            Runnable onChange,
            Runnable onApply,
            Runnable onReset,
            Runnable onCancel) {
        setSpacing(8);
        getStyleClass().add("studio-form-actions");
        changeButton.getStyleClass().add("studio-button-secondary");
        applyButton.getStyleClass().add("studio-button-primary");
        resetButton.getStyleClass().add("studio-button-secondary");
        cancelButton.getStyleClass().add("studio-button-cancel");
        changeButton.setOnAction(ignored -> onChange.run());
        applyButton.setOnAction(ignored -> onApply.run());
        resetButton.setOnAction(ignored -> onReset.run());
        cancelButton.setOnAction(ignored -> onCancel.run());
        getChildren().setAll(changeButton, applyButton, resetButton, cancelButton);
    }

    public void updateState(StudioFormMode mode, boolean dirty) {
        updateState(mode, dirty, true);
    }

    public void updateState(StudioFormMode mode, boolean dirty, boolean canBeginEdit) {
        final boolean editing = mode == StudioFormMode.EDITING;
        setVisibleManaged(changeButton, !editing);
        setVisibleManaged(applyButton, editing);
        setVisibleManaged(resetButton, editing);
        setVisibleManaged(cancelButton, editing);
        changeButton.setDisable(!canBeginEdit);
        applyButton.setDisable(!dirty);
        resetButton.setDisable(!dirty);
    }

    private Button createButton(I18n label) {
        final Button button = new Button();
        button.textProperty().bind(Container.i18n().bind(label));
        button.getStyleClass().add("studio-button");
        return button;
    }

    private void setVisibleManaged(Button button, boolean visible) {
        button.setVisible(visible);
        button.setManaged(visible);
    }
}
