'use strict';

function isObject(value) {
	return (value === Object(value));
}

function makeArrayKey(key) {
	if (key.length > 2 && key.lastIndexOf('[]') === key.length - 2) {
		return key
	} else {
		return key + '[]'
	}
}

function generateKey(prefix, key) {
	if (prefix == null || prefix.length === 0) {
		return key;
	} else {
		return `${prefix}[${key}]`
	}
}

module.exports = function deconstructFormObject(object, prefix) {
	return Object.keys(object).reduce((items, key) => {
		let value = object[key];
		let newItems = [];

		function transformValue(value, isInArray) {
			let valueKey;

			if (isInArray) {
				valueKey = makeArrayKey(generateKey(prefix, key));
			} else {
				valueKey = generateKey(prefix, key);
			}

			if (Array.isArray(value)) {
				value.forEach((arrayItem) => {
					transformValue(arrayItem, true);
				});
			} else if (isObject(value)) {
				newItems = newItems.concat(deconstructFormObject(value, valueKey));
			} else {
				newItems.push({
					name: valueKey,
					value: value
				});
			}
		}

		transformValue(value);

		return items.concat(newItems);
	}, []);
};
