/* ************************************************************************
#
#  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.update;

import java.util.ArrayList;
import java.util.List;

import divconq.db.IDatabaseManager;
import divconq.db.UpdateRequest;
import divconq.lang.OperationResult;
import divconq.struct.RecordStruct;
import divconq.struct.Struct;
import divconq.util.StringUtil;

/**
 * Insert a new record into dcDatabase, see dcInsertRecord schema.
 * 
 * @author Andy
 *
 */
public class InsertRecordRequest extends UpdateRequest {
	protected List<DbField> fields = new ArrayList<DbField>();
	
	/**
	 * @param table name
	 * @param fields to add
	 */
	public InsertRecordRequest(String table, DbField... fields) {
		this(table, null, null, fields);
	}
	
	/**
	 * @param table name
	 * @param filter name 
	 * @param fields to add
	 */
	public InsertRecordRequest(String table, String filter, DbField... fields) {
		this(table, filter, null, fields);
	}
	
	/**
	 * @param table name
	 * @param filter name 
	 * @param extra parameters for filter
	 * @param fields to add
	 */
	public InsertRecordRequest(String table, String filter, Struct extra, DbField... fields) {
		super("dcInsertRecord");
		
		RecordStruct params = new RecordStruct();
		
		this.parameters = params;
	
		params.setField("Table", table);
		
		if (StringUtil.isNotEmpty(filter))
			params.setField("Filter", filter);
		
		if (extra != null)
			params.setField("Extra", extra);
		
		if (fields != null)
			for (DbField fld : fields)
				this.addField(fld);		
	}
	
	/**
	 * @param fld data about a field to store in the table 
	 */
	public void addField(DbField fld) {
		this.fields.add(fld);  
	}
	
	/* (non-Javadoc)
	 * @see divconq.db.UpdateRequest#getDatabaseParams()
	 */
	@Override
	public RecordStruct getDatabaseParams(IDatabaseManager dbm) {
		RecordStruct flds = new RecordStruct();
		
		for (DbField fld : this.fields) 
			flds.setField(fld.getName(), fld.convert(flds, dbm));
		
		this.parameters.setField("Fields", flds);
		
		return this.parameters;
	}
	
	/* (non-Javadoc)
	 * @see divconq.db.UpdateRequest#validate(divconq.lang.OperationResult)
	 */
	@Override
	public void validate(OperationResult or) {
		super.validate(or);
		
		// TODO validate, prove that all fields/tables/filters are real
		// (check filter is for this table)
	}
}
