package p.studio.utilities.logspane;

import javafx.application.Platform;
import javafx.beans.value.ObservableValue;
import javafx.scene.control.TextArea;
import javafx.scene.control.TitledPane;
import p.studio.controls.lifecycle.StudioControlLifecycle;
import p.studio.controls.lifecycle.StudioControlLifecycleSupport;

import java.util.Objects;

public abstract class LogsPane implements StudioControlLifecycle {
    private final TextArea textArea;
    private final TitledPane pane;

    protected LogsPane(
            ObservableValue<String> titleBinding,
            String workspace) {
        this(titleBinding, workspace, true);
    }

    protected LogsPane(
            ObservableValue<String> titleBinding,
            String workspace,
            boolean installLifecycle) {
        final String workspaceName = Objects.requireNonNull(workspace, "workspace").trim();
        if (workspaceName.isBlank()) {
            throw new IllegalArgumentException("workspace must not be blank");
        }

        this.textArea = new TextArea();
        textArea.setEditable(false);
        textArea.setWrapText(true);
        textArea.setPrefRowCount(8);
        textArea.getStyleClass().add("%s-workspace-logs".formatted(workspaceName));

        this.pane = new TitledPane();
        pane.textProperty().bind(Objects.requireNonNull(titleBinding, "titleBinding"));
        pane.setContent(textArea);
        pane.setCollapsible(true);
        pane.setExpanded(true);
        pane.getStyleClass().add("%s-workspace-logs-pane".formatted(workspaceName));
        if (installLifecycle) {
            StudioControlLifecycleSupport.install(pane, this);
        }
    }

    public final TitledPane getPane() {
        return pane;
    }

    protected final void appendLine(String line) {
        final String normalized = Objects.requireNonNullElse(line, "").stripTrailing();
        if (normalized.isBlank()) {
            return;
        }
        Platform.runLater(() -> textArea.appendText(normalized + System.lineSeparator()));
    }

    protected final void clearLogs() {
        Platform.runLater(textArea::clear);
    }
}
