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.WorkspaceDockPane;
import p.studio.controls.lifecycle.StudioControlLifecycle;
import p.studio.controls.lifecycle.StudioControlLifecycleSupport;

import java.util.Objects;

public abstract class LogsPane extends WorkspaceDockPane implements StudioControlLifecycle {
    private static final double COLLAPSED_HEIGHT = 34.0;
    private static final double MINIMUM_EXPANDED_HEIGHT = 120.0;
    private static final double DEFAULT_EXPANDED_HEIGHT = 180.0;

    private final TextArea textArea;

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

    protected LogsPane(
            ObservableValue<String> titleBinding,
            String workspace,
            boolean installLifecycle) {
        super(
                Objects.requireNonNull(titleBinding, "titleBinding"),
                COLLAPSED_HEIGHT,
                MINIMUM_EXPANDED_HEIGHT,
                DEFAULT_EXPANDED_HEIGHT,
                true,
                "%s-workspace-logs-pane".formatted(normalizeWorkspaceName(workspace)));

        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));

        setDockContent(textArea);
        if (installLifecycle) {
            StudioControlLifecycleSupport.install(this, this);
        }
    }

    public final TitledPane getPane() {
        return this;
    }

    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);
    }

    private static String normalizeWorkspaceName(final String workspace) {
        final String workspaceName = Objects.requireNonNull(workspace, "workspace").trim();
        if (workspaceName.isBlank()) {
            throw new IllegalArgumentException("workspace must not be blank");
        }
        return workspaceName;
    }
}
