define(['knockout', 'models/Field'], function(ko, Field) {
/**
* This is a recursive function that will instantiate
* the JSON fields coming from the server into a Field object
* @module app/helpers/inflateFields
* @param {Array} container Store the inflated template fields here
* @param {Array} fields Fields to inflate
* @param {Object} parent The parent field of the current field in the loop
* @returns {Array}
* @requires knockout
* @requires app/models/Field
*
*/
function inflateFields(container, fields, parent, showControls, copyField) {
var currentField = null,
childFields = [];
fields = fields instanceof Array ? fields : [fields];
copyField = copyField || false;
container = container || [];
showControls = typeof showControls === 'undefined' ? true : showControls;
ko.utils.arrayForEach(fields, function(field, i) {
if (copyField) {
field.parent = parent ? parent.name : null;
delete field.name;
delete field.id;
}
field.showControls = showControls;
currentField = new Field(field);
if (field.childFields.length) {
inflateFields(container, field.childFields, currentField, showControls, copyField);
}
if (!field.parent) {
container.push(currentField);
}
if (parent) {
childFields = parent.childFields();
childFields.splice(i, 0, currentField);
parent.childFields.valueHasMutated();
// parent.childFields.push(currentField);
}
});
return container;
}
return inflateFields;
})