/**
 * Add global dynamic tags
 */
( function( wp ) {

	const {
		addFilter
	} = wp.hooks;

	const {
		has,
		isEmpty
	} = lodash;

	function addTagOptions( options ) {

		// loop through posttypes
		greyd.data.post_types.forEach( posttype => {
			if ( has( posttype, 'arguments' ) && has( posttype.arguments, 'is_global_dynamic_tag' ) ) {

				let posttypeOptions = [];

				const {
					singular,
					slug,
					fields = [],
					icon = 'admin-post'
				} = posttype;

				// loop through fields
				fields.forEach( field => {

					const {
						name,
						label,
						type
					} = field;
					
					// not a field with a value
					if (
						isEmpty( name )
						|| type == 'headline'
						|| type == 'descr'
						|| type == 'hr'
					) {
						return; // continue
					}

					// push field to posttype options
					posttypeOptions.push( {
						value: 'gdt-' + slug + '-' + name,
						label: isEmpty( label ) ? name : label,
						icon: icon,
						keywords: [ 'posttype', 'global' ]
					} )
				});

				// push all posttype options as dynamic options
				if ( posttypeOptions.length ) {
					options.push( {
						label: singular,
						options: posttypeOptions
					} );
				}
			}
		});
		
		return options;
	}

	addFilter(
		'greyd.dynamic.tags.getRichTextOptions',
		'greyd/hook/dynamic/tagOptions',
		addTagOptions
	);

	function addTriggerOptions( options ) {

		// loop through posttypes
		greyd.data.post_types.forEach( posttype => {
			if ( has( posttype, 'arguments' ) && has( posttype.arguments, 'is_global_dynamic_tag' ) ) {

				let posttypeOptions = [];

				const {
					singular,
					slug,
					fields,
					icon
				} = posttype;

				// loop through fields
				fields.forEach( field => {

					const {
						name,
						label,
						type
					} = field;
					
					// not a field with a value
					if ( isEmpty( name ) ) {
						return; // continue
					}

					if ( type == 'url' ) {
						// push field to posttype options
						posttypeOptions.push( {
							value: 'gdt-' + slug + '-' + name,
							label: isEmpty( label ) ? name : label,
							icon: icon,
							keywords: [ 'posttype', 'global' ]
						} )
					}
					else if ( type == 'file' ) {
						// push field to posttype options
						posttypeOptions.push( {
							value: 'gdt-' + slug + '-' + name,
							label: __( "link to the file:", 'greyd_hub' ) +' '+ ( isEmpty( label ) ? name : label ),
							icon: icon,
							keywords: [ 'posttype', 'global' ]
						} )
					}

				});

				// push all posttype options as dynamic options
				if ( posttypeOptions.length ) {
					options.push( {
						label: singular,
						options: posttypeOptions
					} );
				}
			}
		});
		
		return options;
	}

	addFilter(
		'greyd.dynamic.triggerOptions',
		'greyd/hook/dynamic/triggerOptions',
		addTriggerOptions
	);

} )( 
	window.wp
);