package io.xpipe.app.comp.base;

import io.xpipe.app.comp.BaseRegionBuilder;
import io.xpipe.app.comp.RegionBuilder;

import javafx.geometry.Pos;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.Region;

import atlantafx.base.layout.InputGroup;

import java.util.List;

public class InputGroupComp extends RegionBuilder<InputGroup> {

    private final List<BaseRegionBuilder<?, ?>> entries;

    private BaseRegionBuilder<?, ?> mainReference;

    public InputGroupComp(List<BaseRegionBuilder<?, ?>> comps) {
        entries = List.copyOf(comps);
    }

    public InputGroupComp setMainReference(BaseRegionBuilder<?, ?> mainReference) {
        this.mainReference = mainReference;
        return this;
    }

    public InputGroupComp setMainReference(int index) {
        return setMainReference(entries.get(index));
    }

    @Override
    public InputGroup createSimple() {
        InputGroup b = new InputGroup();
        b.getStyleClass().add("input-group-comp");
        for (var entry : entries) {
            b.getChildren().add(entry.build());
        }
        b.setAlignment(Pos.CENTER);

        if (mainReference != null && entries.contains(mainReference)) {
            var refIndex = entries.indexOf(mainReference);
            var ref = b.getChildren().get(refIndex);
            HBox.setHgrow(ref, Priority.ALWAYS);
            if (ref instanceof Region refR) {
                for (int i = 0; i < entries.size(); i++) {
                    if (i == refIndex) {
                        continue;
                    }

                    var entry = b.getChildren().get(i);
                    if (!(entry instanceof Region entryR)) {
                        continue;
                    }

                    entryR.minHeightProperty().bind(refR.heightProperty());
                    entryR.maxHeightProperty().bind(refR.heightProperty());
                    entryR.prefHeightProperty().bind(refR.heightProperty());
                }
            }

            b.focusedProperty().addListener((observable, oldValue, newValue) -> {
                if (newValue) {
                    ref.requestFocus();
                }
            });
        }

        return b;
    }
}
