/* ************************************************************************
#
#  DivConq
#
#  http://divconq.com/
#
#  Copyright:
#    Copyright 2012 eTimeline, LLC. All rights reserved.
#
#  License:
#    See the license.txt file in the project's top-level directory for details.
#
#  Authors:
#    * Andy White
#
************************************************************************ */
package divconq.db;

import divconq.bus.Message;
import divconq.lang.OperationResult;
import divconq.struct.builder.BuilderState;
import divconq.struct.builder.ICompositeBuilder;

/**
 * Super class that helps manage results from dcDb.  See ObjectResult and
 * CustomResult for specifics.
 * 
 * @author Andy
 *
 */
abstract public class DatabaseResult extends OperationResult {
	protected ICompositeBuilder data = null;
	
	/**
	 * Gets the object that is managing the output stream/structure.
	 * 
	 * @return Stream or Struct builder
	 */
	public ICompositeBuilder getBuilder() {
		return this.data;
	}

	/**
	 * Assign an object to manage the output stream from the database.
	 * 
	 * @param builder Stream or Struct builder 
	 */
	public DatabaseResult(ICompositeBuilder builder) {
		super(false);
		
		this.data = builder;		
	}
	
	/**
	 * Convert the entire result, data and messages, into a Message worthy
	 * to be sent as a reply to a service.  If a service is merely a front to
	 * a stored proc then this may be the natural way to return the result.
	 * 
	 * @return data and messages rolled up into a Message ready for the bus
	 */
	public Message toMessageWithData() {
		Message m = this.toMessage();
		
		if (this.data.getState() == BuilderState.Ready) 
			m.setField("Body", null);
		else
			m.setField("Body", this.data);
		
		return m;
	}
}
