package leigh.elements;

import leigh.elements.sdk.AppScreenInstance;
import leigh.elements.sdk.type1.Element;
import leigh.eo.EO;
import leigh.mecha.log.MechaLogger;
import leigh.mecha.log.MechaLoggerFactory;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * Base implementation for a {@link Element} which contains children in one of its attributes.
 *
 * @author Alex Leigh
 */
public class ParentElement extends ElementBase {
    private static final MechaLogger logger = MechaLoggerFactory.getLogger(ParentElement.class);
    private HashMap<String, ArrayList<Element>> children = new HashMap<>();
    private final AppScreenInstance screen;

    protected ParentElement(EO cfg, AppScreenInstance screen) {
        super(cfg);
        this.screen = screen;
    }

    /**
     * For each child found in the attribute, factory it and add it to our children list to be available
     * via the <code>getChildren()</code> method.
     */
    public void buildChildren(String childrenKey) {
        ArrayList<Element> kids = new ArrayList<>();
        for (EO paneCfg : getCfg().getValueLoop(childrenKey)) {
            logger.debug("Building child: {}", paneCfg);
            Element newChild = screen.getFactory().build(paneCfg, screen);
            kids.add(newChild);
        }
        children.put(childrenKey, kids);
    }

    public AppScreenInstance getScreen() {
        return screen;
    }

    public HashMap<String, ArrayList<Element>> getChildren() {
        return children;
    }
}
