package p.studio.workspaces.builder;

import javafx.geometry.Orientation;
import javafx.scene.Node;
import javafx.scene.control.*;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.StackPane;
import p.studio.Container;
import p.studio.projects.ProjectReference;
import p.studio.shipper.StudioShipperService;
import p.studio.utilities.i18n.I18n;
import p.studio.workspaces.Workspace;
import p.studio.workspaces.WorkspaceId;

public class ShipperWorkspace extends Workspace {
    private final BorderPane root = new BorderPane();
    private final TextArea logs = new TextArea();
    private final Button buildButton = new Button();
    private final Button clearButton = new Button();
    private final StudioShipperService shipperService = new StudioShipperService();

    public ShipperWorkspace(ProjectReference projectReference) {
        super(projectReference);
        final var toolbar = buildToolBar();
        root.setTop(toolbar);

        final var projectArea = buildProjectArea();
        final var logsPane = buildLogsPane();

        final var split = new SplitPane(projectArea, logsPane);
        split.setOrientation(Orientation.VERTICAL);
        split.setDividerPositions(0.5);

        root.setCenter(split);
    }

    @Override
    public WorkspaceId workspaceId() {
        return WorkspaceId.SHIPPER;
    }

    @Override
    public I18n title() {
        return I18n.WORKSPACE_SHIPPER;
    }

    @Override
    public Node rootNode() {
        return root;
    }

    @Override
    public void load() {

    }

    @Override
    public void unLoad() {

    }

    private ToolBar buildToolBar() {
        buildButton.textProperty().bind(Container.i18n().bind(I18n.WORKSPACE_SHIPPER_BUTTON_RUN));
        buildButton.getStyleClass().addAll("studio-button", "studio-button-primary");
        buildButton.setOnAction(e -> {
            logs.clear();
            shipperService.prepare(projectReference, entry -> logs.appendText(
                    "[%s] %s%s".formatted(entry.source().name(), entry.message(), System.lineSeparator())));
        });

        clearButton.textProperty().bind(Container.i18n().bind(I18n.WORKSPACE_SHIPPER_BUTTON_CLEAR));
        clearButton.getStyleClass().addAll("studio-button", "studio-button-secondary");
        clearButton.setOnAction(e -> logs.clear());

        return new ToolBar(buildButton, clearButton);
    }

    private StackPane buildProjectArea() {
        final var tmpLabel = new Label("Project: " + projectReference.name());
        return  new StackPane(tmpLabel);
    }

    private TitledPane buildLogsPane() {
        logs.setEditable(false);
        logs.setWrapText(true);
        logs.setMinHeight(350);

        final var pane = new TitledPane();
        pane.setContent(logs);
        pane.textProperty().bind(Container.i18n().bind(I18n.WORKSPACE_SHIPPER_LOGS));
        pane.setCollapsible(true);
        pane.setExpanded(true);

        return pane;
    }
}
