/**
 * BLOCK: sbd-block
 *
 * Registering a basic block with Gutenberg.
 * Simple block, renders and saves the same content without any interactivity.
 */

//  Import CSS.
import './style.scss';
import './editor.scss';

const { __ } = wp.i18n; // Import __() from wp.i18n
const { registerBlockType } = wp.blocks; // Import registerBlockType() from wp.blocks


registerBlockType( 'sbd/block-sbd-block', {
	// Block name. Block names must be string that contains a namespace prefix. Example: my-plugin/my-custom-block.
	title: __( 'SBD - Shortcode Generator' ), // Block title.
	icon: 'shield', // Block icon from Dashicons → https://developer.wordpress.org/resource/dashicons/.
	category: 'common', // Block category — Group blocks together based on common traits E.g. common, formatting, layout widgets, embed.
	keywords: [
		__( 'SBD — Shortcode Generator' ),
		__( 'SBD — Shortcode Generator' ),
	],
	attributes: {
        shortcode: {
            type: 'string',
            default: 0
        }
    },


	
	edit: function( props ) {
		const { attributes: { shortcode }, setAttributes } = props;

		function showShortcodeModal(e){
			 jQuery('#sbd_shortcode_generator_meta_block').prop('disabled', true);
			 jQuery(e.target).addClass('currently_editing');
			jQuery.post(
				ajaxurl,
				{
					action : 'show_qcpd_shortcodes'
					
				},
				function(data){
					jQuery('#sbd_shortcode_generator_meta_block').prop('disabled', false);
					jQuery('#wpwrap').append(data);
					jQuery('#wpwrap').find('#sm-modal .sbd_copy_close').removeClass('sbd_copy_close').addClass('sbd_block_copy_close');
				}
			)
		}

		function insertShortCode(e){
			const shortcode = jQuery('#sbd_shortcode_container').val();
			setAttributes( { shortcode: shortcode } );
			//jQuery('#wpwrap').find('#sm-modal').remove();
			console.log({ shortcode });
		}

		jQuery(document).on('click','.sbd_block_copy_close', function(e){
			e.preventDefault();
			jQuery('.currently_editing').next('#insert_shortcode').trigger('click');
			jQuery(document).find( '.modal-content .close').trigger('click');
		});

		jQuery(document).on( 'click', '.modal-content .close', function(){
			jQuery('.currently_editing').removeClass('currently_editing');
		});

		
        return (
            <div className={ props.className }>
				<input type="button" id="sbd_shortcode_generator_meta_block" onClick={showShortcodeModal} className="button button-primary button-large" value="Generate SBD Shortcode" />
				<input type="button" id="insert_shortcode" onClick={insertShortCode} className="button button-primary button-large" value="Test SBD Shortcode" />
				<br />
				{ shortcode }
			</div>
        );
	},


	
	save: function( props ) {
		const { attributes: { shortcode } } = props;
		return (
			<div>
				{shortcode}
			</div>
		);
	},
} );
