package leigh.elements.javafx.type1;

import javafx.scene.Node;
import javafx.scene.control.TitledPane;
import javafx.scene.layout.VBox;
import leigh.elements.ElementsSort;
import leigh.elements.ParentElement;
import leigh.elements.sdk.AppScreenInstance;
import leigh.elements.sdk.type1.Element;
import leigh.elements.sdk.type1.PanelElement;
import leigh.eo.EO;
import leigh.mecha.log.MechaLogger;
import leigh.mecha.log.MechaLoggerFactory;

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

/**
 * Implementation of the {@link PanelElement} for JavaFX.
 * <p>
 * Limitations: This implementation does not track changes to its configuration, and so will not mutate if that
 * configuration changes, including the <code>PanelElement.KEY_CONTENT</code>.
 *
 * @author Alex Leigh
 */
public class PanelElementJFX extends ParentElement implements ElementJFX {
    private static final MechaLogger logger = MechaLoggerFactory.getLogger(PanelElementJFX.class);
    private TitledPane root;

    protected PanelElementJFX(EO cfg, AppScreenInstance controller) {
        super(cfg, controller);
        buildChildren(PanelElement.KEY_CONTENT);
    }

    @Override
    public Node getJavaFXNode() {
        root = new TitledPane();
        root.setText(getCfg().getValueString(PanelElement.KEY_LABEL));
        VBox content = new VBox();
        root.setContent(content);

        // FIXME: Set Locale properly
        ArrayList<Element> children = ElementsSort.sort(
                getChildren().get(PanelElement.KEY_CONTENT),
                "uiIndex", Locale.ENGLISH);

        for (Element child : children) {
            if (child instanceof ElementJFX) {
                logger.debug("Adding child node: [idx: {}] [node: {}]", child.getCfg().get("uiIndex"), child);
                content.getChildren().add(((ElementJFX) child).getJavaFXNode());
            }
        }

        return root;
    }
}
