package leigh.elements.javafx.type1;

import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.control.Label;
import javafx.scene.layout.GridPane;
import leigh.elements.ElementsSort;
import leigh.elements.ParentElement;
import leigh.elements.sdk.AppScreenInstance;
import leigh.elements.sdk.type1.Element;
import leigh.elements.sdk.type1.FormLayout;
import leigh.elements.sdk.type1.TextFieldElement;
import leigh.eo.EO;
import leigh.mecha.log.MechaLogger;
import leigh.mecha.log.MechaLoggerFactory;

import java.util.ArrayList;
import java.util.Locale;

/**
 * Implementation of a FormLayoutElement for JavaFX.
 *
 * @author Alex Leigh
 */
public class FormLayoutJFX extends ParentElement implements ElementJFX {
    private static final MechaLogger logger = MechaLoggerFactory.getLogger(FormLayoutJFX.class);
    GridPane grid = new GridPane();

    protected FormLayoutJFX(EO cfg, AppScreenInstance controller) {
        super(cfg, controller);
        grid.setAlignment(Pos.CENTER);
        grid.setHgap(10);
        grid.setVgap(10);
        grid.setPadding(new Insets(25, 25, 25, 25));

        buildChildren(FormLayout.KEY_FIELDS);

        int row = 0;

        logger.debug("Found fields: {}", getChildren());

        ArrayList<Element> children = ElementsSort.sort(
                getChildren().get(FormLayout.KEY_FIELDS),
                "uiIndex", Locale.ENGLISH);

        for (Element field : children) {
            String label = field.getCfg().getValueString(TextFieldElement.KEY_LABEL);
            Label l = new Label(label + ":");
            grid.add(l, 0, row);
            grid.add(((ElementJFX) field).getJavaFXNode(), 1, row);
            row++;
        }
    }

    @Override
    public Node getJavaFXNode() {
        return grid;
    }
}
