/**
 * Get podcasts block attributes 
 */
export function getPodcastsAttributes() {
	return getAttributes( aiopod_blocks.podcasts );
}

/**
 * Get episodes block attributes 
 */
export function getEpisodesAttributes() {
	return getAttributes( aiopod_blocks.episodes );
}

/**
 * Get categories block attributes 
 */
export function getCategoriesAttributes() {
	return getAttributes( aiopod_blocks.categories );
}

/**
 * Get tags block attributes 
 */
export function getTagsAttributes() {
	return getAttributes( aiopod_blocks.tags );
}

/**
 * Get participants block attributes 
 */
export function getParticipantsAttributes() {
	return getAttributes( aiopod_blocks.participants );
}

/**
 * Group terms by parent
 */
export function GroupByParent( terms ) {
	var map = {}, node, roots = [];
	
	for ( var i = 0; i < terms.length; i += 1 ) {
		map[ terms[ i ].id ] = i; // Initialize the map
		terms[ i ].children = []; // Initialize the children		
	}	

	for ( var i = 0; i < terms.length; i += 1 ) {
		node = terms[ i ];
		if ( node.parent == 0 ) {
			roots.push( node );			
		} else if ( map.hasOwnProperty( node.parent ) ) {
			terms[ map[ node.parent ] ].children.push( node );
		}
	}	

	return roots;
}

/**
 * Build tree array from flat array
 */
export function BuildTree( terms, tree = [], prefix = '' ) {
	for ( var i = 0; i < terms.length; i += 1 ) {
		tree.push({
			label: prefix + terms[ i ].name.replace( /&amp;/g, '&' ),
			value: terms[ i ].id,
		});	

		if ( terms[ i ].children.length > 0 ) {
			BuildTree( terms[ i ].children, tree, prefix.trim() + '— ' );
		}
	}	

	return tree;
}

/**
 * Get attributes 
 */
function getAttributes( items ) {
	var attributes = {};
	
	for ( var key in items ) {
		var fields = items[ key ].fields;

		for ( var field in fields ) {
			var name = fields[ field ].name;

			attributes[ name ] = {
				type: getAttributeType( fields[ field ].type ),
				default: fields[ field ].value
			};
		}
	}

	return attributes;
}

/**
 * Get attribute type
 */
function getAttributeType( type ) {
	var __type = 'string';

	if ( 'categories' == type || 'tags' == type || 'participants' == type ) {
		__type = 'array';
	} else if ( 'number' == type ) {
		__type = 'number';
	} else if ( 'checkbox' == type ) {
		__type = 'boolean';
	}

	return __type;
}
