package leigh.elements.javafx.type1;

import javafx.scene.Node;
import javafx.scene.layout.FlowPane;
import leigh.elements.ElementsSort;
import leigh.elements.ParentElement;
import leigh.elements.sdk.AppScreenInstance;
import leigh.elements.sdk.type1.Element;
import leigh.elements.sdk.type1.GridElement;
import leigh.eo.EO;
import leigh.eo.EOLoop;
import leigh.eo.EOLoopListener;
import leigh.eo.EditEventGenerator;
import leigh.mecha.log.MechaLogger;
import leigh.mecha.log.MechaLoggerFactory;

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

/**
 * This class provides the JavaFX implementation for the {@link GridElement}.
 *
 * @author Alex Leigh
 */
public class GridElementJFX extends ParentElement implements ElementJFX, EOLoopListener {
    private static final MechaLogger logger = MechaLoggerFactory.getLogger(GridElementJFX.class);
    private FlowPane grid = new FlowPane();

    protected GridElementJFX(EO cfg, AppScreenInstance screen) {
        super(cfg, screen);

        EOLoop content = cfg.getValueLoop(GridElement.KEY_CONTENT);
        ((EditEventGenerator) cfg.getEditTracker()).addLoopListener(content, this);
        grid.getStyleClass().add("leigh-elements-grid");
        update();
    }

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

    private void update() {
        // Build the configs for our children - stored in KEY_CONTENT
        grid.getChildren().clear();

        logger.debug("Child size: {}", getChildren().size());
        buildChildren(GridElement.KEY_CONTENT);

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

        // Sort our children based on their uiIndex
        ArrayList<Element> children = ElementsSort.sort(
                getChildren().get(GridElement.KEY_CONTENT),
                "uiIndex", Locale.ENGLISH);

        for (Element field : children) {
            logger.debug("child: {}", field);
            grid.getChildren().add(((ElementJFX) field).getJavaFXNode());
        }
    }

    @Override
    public void removed(EOLoop loop, EO obj, int index) {
        update();
    }

    @Override
    public void added(EOLoop loop, EO obj) {
        update();
    }
}
