package leigh.conflux.nodegraph;

import leigh.conflux.DataSource;
import leigh.conflux.DataSourceBinder;
import leigh.eo.EOLoop;
import leigh.mecha.log.MechaLogger;
import leigh.mecha.log.MechaLoggerFactory;
import leigh.mecha.nodegraph.Node;
import leigh.mecha.nodegraph.ProcessorState;
import leigh.mecha.nodegraph.UselessAttribute;

/**
 * A graph node for loading object data into a Conflux graph from a foreign system via a {@link DataSource} object.
 * It is up to the individual implementation to provide the mechanics for getting rows into this node for the
 * purposes of processing the model.
 * <p>
 * The node provides the <code>KEY_IN_NAME</code> attribute, which when read should provide the name of the
 * datasource to be read by the node.
 *
 * @author Alex Leigh
 */
public class RecordSetNode extends Node {
    private static final MechaLogger logger = MechaLoggerFactory.getLogger(RecordSetNode.class);
    public final static String KEY_OUT_OBJS = "objs";
    public final static String KEY_IN_NAME = "name";
    // FIXME: This is the wrong namespace
    public static final String NODE_NAME = "qody.vision.v1.RecordSet";

    /**
     * Create a new DataSourceCode which wraps the provided {@link DataSource}. The <code>DataSource.getData()</code>
     * method will be called whenever this nodes <code>KEY_OUT_ROWS</code> property is read, so this node returns
     * the actual datasource (not a copy).
     */
    public RecordSetNode(String id, DataSourceBinder binder) {
        super(id);
        addOutput(KEY_OUT_OBJS, new UselessAttribute() {
            public EOLoop getObjectsValue(ProcessorState state) throws Exception {
                String dsName = getInputSingleString(KEY_IN_NAME, state);
                logger.debug("Reading objs. [name: {}]", dsName);
                if (dsName != null) {
                    DataSource ds = binder.getDataSource(dsName);
                    logger.debug("Located datasource: {}", ds);
                    if (ds != null) {
                        //  logger.debug("Read node from instance. {}", ds.getData().hashCode());
                        return ds.getData();
                    }
                }
                logger.warn("Unable to obtain a rowset.");
                return null;
            }
        });
    }
}
