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

/**
 * Update a record in dcDatabase, see dcUpdateRecord schema.
 * Limit to 1MB of values (total size)
 * 
 * @author Andy
 *
 */
public class UpdateRecordRequest extends UpdateRequest {
	protected List<DbField> fields = new ArrayList<DbField>();
	
	/**
	 * @param table name
	 * @param fields to update
	 */
	public UpdateRecordRequest(String table, String id, DbField... fields) {
		this(table, id, null, null, fields);
	}
	
	/**
	 * @param table name
	 * @param filter name
	 * @param fields to update
	 */
	public UpdateRecordRequest(String table, String id, String filter, DbField... fields) {
		this(table, id, filter, null, fields);
	}
	
	/**
	 * @param table name
	 * @param filter name
	 * @param extra params for filter
	 * @param fields to update
	 */
	public UpdateRecordRequest(String table, String id, String filter, Struct extra, DbField... fields) {
		super("dcUpdateRecord"); 
		
		RecordStruct params = new RecordStruct();
		
		this.parameters = params;
	
		params.setField("Table", table);
		params.setField("Id", id);
		
		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#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)
	}
	
	/* (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;
	}
}
