package leigh.conflux.nodegraph;

import leigh.eo.EO;
import leigh.eo.EOLoop;
import leigh.mecha.nodegraph.Attribute;
import leigh.mecha.nodegraph.Node;
import leigh.mecha.nodegraph.ProcessorState;
import leigh.mecha.nodegraph.UselessAttribute;

import java.util.ArrayList;

/**
 * This node produces a new rowset from a n rowsets, by combining objects in each set. The new set contains
 * new EOs.
 *
 * @author Alex Leigh
 */
public class MergeNode extends Node {
    public static final String KEY_INPUT_ROWS = "rows";
    public static final String KEY_OUTPUT_ROWS = "rows";

    public MergeNode(String id) {
        super(id);
        addOutput(KEY_OUTPUT_ROWS, new UselessAttribute() {
            public EOLoop getObjectsValue(ProcessorState state) throws Exception {
                ArrayList<EOLoop> loops = new ArrayList<>();
                for (Attribute a : getInputs(KEY_INPUT_ROWS)) {
                    EOLoop loop = a.getObjectsValue(state);
                    if (loop != null) loops.add(loop);
                }

                EOLoop newLoop = new EOLoop();

                for (int i = 0; i < loops.get(0).size(); i++) {
                    newLoop.add(merge(loops, i));
                }

                return newLoop;
            }
        });
    }

    private EO merge(ArrayList<EOLoop> loops, int idx) {
        EO merged = new EO();

        for (EOLoop loop : loops) {
            EO obj = loop.get(idx);
            merged.setAll(obj);
        }

        return merged;
    }
}
