import classnames from 'classnames';
import { __ } from '@wordpress/i18n';
import { addFilter } from '@wordpress/hooks'; 
import { registerBlockStyle } from '@wordpress/blocks';
import { createHigherOrderComponent } from '@wordpress/compose';
import { ToggleControl } from "@wordpress/components";
import {
	InspectorControls
} from '@wordpress/block-editor';

import "./editor.scss";
import "./style.scss";

function addAttributes( settings ) {
	if ( settings.name !== 'core/gallery' ) {
		return settings;
	}
  //check if object exists for old Gutenberg version compatibility
	if( typeof settings.attributes !== 'undefined' ){
	
		settings.attributes = Object.assign( settings.attributes, {
			loadMore:{ 
				type: 'boolean',
				default: false,
			}
		});
    
	}

	return settings;
}

/**
 * Add mobile visibility controls on Advanced Block Panel.
 *
 * @param {function} BlockEdit Block edit component.
 *
 * @return {function} BlockEdit Modified block edit component.
 */
const withAdvancedControls = createHigherOrderComponent( ( BlockEdit ) => {
  return ( props ) => {

		const {
			name,
			attributes,
			setAttributes,
			isSelected,
		} = props;

		const {
			loadMore,
		} = attributes;
		
		
		return (
			<>
				<BlockEdit {...props} />
				{ isSelected && name === 'core/gallery' &&
					<InspectorControls group="advanced">
						<ToggleControl
							label={ __( 'Enable Load More' ) }
							checked={ !! loadMore }
							onChange={ () => setAttributes( {  loadMore: ! loadMore } ) }
              __nextHasNoMarginBottom
						/>
					</InspectorControls>
				}

			</>
		);
	};
}, 'withAdvancedControls');

function applyExtraClass( extraProps, blockType, attributes ) {

	const { loadMore } = attributes;
	
	//check if attribute exists for old Gutenberg version compatibility
	//add class only when visibleOnMobile = false
	if ( typeof loadMore !== 'undefined' && loadMore &&  blockType.name === 'core/gallery'  ) {
		extraProps.className = classnames( extraProps.className, 'load-more-gallery' );
	}

	return extraProps;
}

addFilter(
	'blocks.registerBlockType',
	'ucla-wordpress-plugin/gallery-load-more',
	addAttributes
);
addFilter(
	'editor.BlockEdit',
	'ucla-wordpress-plugin/custom-advanced-control',
	withAdvancedControls
);

addFilter(
	'blocks.getSaveContent.extraProps',
	'ucla-wordpress-plugin/applyExtraClass',
	applyExtraClass
);

registerBlockStyle("core/gallery", {
  name: "masonry",
  label: __("Masonry"),
});