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

import divconq.db.IDatabaseManager;
import divconq.db.UpdateRequest;
import divconq.db.update.DynamicListField;
import divconq.db.update.DynamicScalarField;
import divconq.lang.BigDateTime;
import divconq.struct.ListStruct;
import divconq.struct.RecordStruct;
import divconq.struct.Struct;

/**
 * Insert a new group record into dcDatabase.  Name is required.
 * 
 * @author Andy
 *
 */
public class AddGroupRequest extends UpdateRequest {
	protected RecordStruct fields = null;
	
	public void setName(String v) {
		this.fields.setField("dcName", v);
	}
	
	public void addAuthorizationTag(String... tags) {
		ListStruct list = this.fields.getFieldAsList("dcAuthorizationTag");
		
		if (list == null) {
			list = new ListStruct();
			this.fields.setField("dcAuthorizationTag", list);
		}
		
		for (String tag : tags)
			list.addItem(tag);
	}
	
	public AddGroupRequest(RecordStruct fields) {
		super("dcInsertRecord");
		
		this.fields = fields;
	}
	
	public AddGroupRequest(String name) {
		super("dcInsertRecord");
		
		this.fields = new RecordStruct();
		this.setName(name);
	}
	
	/* (non-Javadoc)
	 * @see divconq.db.UpdateRequest#getDatabaseParams()
	 */
	@Override
	public RecordStruct getDatabaseParams(IDatabaseManager dbm) {
		this.parameters = new RecordStruct();	
		this.parameters.setField("Table", "dcGroup");
		
		BigDateTime when = BigDateTime.nowDateTime();
		
		RecordStruct flds = new RecordStruct();
		
		if (!this.fields.isFieldEmpty("dcName")) {
			DynamicScalarField fld = new DynamicScalarField("dcName", null, this.fields.getFieldAsString("dcName"), when);
			flds.setField("dcName", fld.convert(flds, dbm));
		}
		
		if (this.fields.hasField("dcAuthorizationTag")) {
			ListStruct list = this.fields.getFieldAsList("dcAuthorizationTag");
			
			for (Struct tag : list.getItems()) {
				DynamicListField fld = new DynamicListField("dcAuthorizationTag", null, tag, when);
				flds.setField("dcAuthorizationTag", fld.convert(flds, dbm));
			}
		}
		
		this.parameters.setField("Fields", flds);
		
		return this.parameters;
	}
}
